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;
}
};
747

被折叠的 条评论
为什么被折叠?



