题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
思路:1,逐个判断(判断数a是否为丑数,将a除以2,除以3,除以5直到除不尽为止,若余数为1则为丑数;2,维护一个丑数排序数组,一个丑数乘以2或者3或者5肯定还是丑数,取最小的数放入数组,将该最小数对应的乘数位置加1。依次计算,找到第index个丑数)
int GetUglyNumber_Solution(int index) {
if(index<=1)
return index;
int newNum = 1;
int count = 1;
vector<int> temp;//顺序存放丑数
temp.push_back(1);
int x=0,y=0,z=0;
while(count<index)
{
temp.push_back(std::min(2*temp[x],min(3*temp[y],5*temp[z])));
if(temp[x]*2==temp[count])
x++;
if(temp[y]*3==temp[count])
y++;
if(temp[z]*5==temp[count])
z++;
count++;
}
return temp[index-1];
}