題目描述
把只包含質因子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];
}