1,题目要求
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
2,题目思路
对于这道题,要求判断从小到大第N个丑数。
所谓丑数,是因子只含有2、3、5的数字。
在丑数的寻找上,我们只去比较三个数:
用于乘2的最小的数、用于乘3的最小的数,用于乘5的最小的数。也就是比较(2 * x , 3 * y, 5 * z) ,x>=y>=z
3,代码实现
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if(index < 7)
return index;
vector<int> res (index, -1);
res[0] = 1;
int idx2 = 0, idx3 = 0, idx5 = 0;
for(int i = 1;i<index;i++){
res[i] = min(res[idx2]*2, min(res[idx3]*3, res[idx5]*5));
if(res[i] == res[idx2]*2) idx2++;
if(res[i] == res[idx3]*3) idx3++;
if(res[i] == res[idx5]*5) idx5++;
}
return res[index-1];
}
};