[leetcode] Ugly Number II

来源:互联网 发布:微信mac安装包dmg 编辑:程序博客网 时间:2024/04/30 00:12

from : https://leetcode.com/problems/ugly-number-ii/

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

class Solution {public:    int nthUglyNumber(int n) {        if(1 >= n) return 1;        int* uglies = new int[n];                uglies[0] = 1;        int i = 1, i2=0, i3=0, i5=0;        while(i < n) {            int min = Min(uglies[i2]*2, uglies[i3]*3, uglies[i5]*5);            uglies[i++] = min;            while(uglies[i2]*2 <= min) ++i2;            while(uglies[i3]*3 <= min) ++i3;            while(uglies[i5]*5 <= min) ++i5;        }                i = uglies[n-1];        delete[] uglies;        return i;    }        int Min(int a, int b, int c) {        if(a < b) {            if(a < c) return a;        } else {            if(b < c) return b;        }        return c;    }};


0 0
原创粉丝点击