设计一个算法,找出只含素因子2
,3
,5
的第 n 大的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
注意事项
我们可以认为1
也是一个丑数
如果n = 9
, 返回 10
class Solution {
public:
/*
* @param n an integer
* @return the nth prime number as description.
*/
int nthUglyNumber(int n) {
// write your code here
int count = 1;
vector<int> ugly(n,0);
ugly[0] = 1;
vector<int> idx(3,0);
while(count < n)
{
int a = 2 * ugly[idx[0]];
int b = 3 * ugly[idx[1]];
int c = 5 * ugly[idx[2]];
int temp = min(min(a, b), c);
if(temp == a)
++idx[0];
if(temp == b)
++idx[1];
if(temp == c)
++idx[2];
ugly[count] = temp;
++count;
}
return ugly[n-1];
}
};