题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
分析
用数组来保存求过的丑数,后面的丑数等于前面的丑数乘于2 3 5。
代码
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if(index<1) return 0;
vector<int> res(index,1);
int p2=0,p3=0,p5=0;
for(int i=1;i<index;++i){
int temp2=res[p2]*2;
int temp3=res[p3]*3;
int temp5=res[p5]*5;
if(temp2<=temp3&&temp2<=temp5){
res[i]=temp2;
++p2;
if(temp2==temp3)
++p3;
if(temp2==temp5)
++p5;
continue;
}
if(temp3<=temp2&&temp3<=temp5){
res[i]=temp3;
++p3;
if(temp3==temp2)
++p2;
if(temp3==temp5)
++p5;
continue;
}
if(temp5<=temp2&&temp5<=temp3){
res[i]=temp5;
++p5;
if(temp5==temp2)
++p2;
if(temp5==temp3)
++p3;
continue;
}
}
return res[index-1];
}
};