一、題目(中等)
編寫一個程序,找出第 n
個醜數。
醜數就是隻包含質因數 2, 3, 5
的正整數。
示例:
輸入: n = 10
輸出: 12
解釋: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
是前 10 個醜數。
說明:
1
是醜數。n
不超過1690。
二、題解思路
- 題解思路1:在Leetcode——263.醜數的思想下進行循環,找到第n個醜數,但是這樣會產生大量計算,在不是醜數的數上耗時很大,因此結果也可想而知,最後在計算第1500往後時,出現超時的情況。
- 題解思路2:三指針法:
- 定義兩個vector數組,一個是存按順序不斷存入的醜數(nums),另一個(ThreeIndex)是存與2、3、5有關的3索引(對應醜數數組中);
- 使用3個索引對應的醜數數組中的值與2、3、5分別相乘,對於2,其與nums[ThreeIndex[0]]相乘,對於3,其與nums[ThreeIndex[1]]相乘,對於5,其與nums[ThreeIndex[2]]相乘;
- 對於他們三個的乘積結果,取其中最小的一個數作爲下一個醜數,只要他們中的2或3或5命中了下一個醜數,則2或3或5對應的ThreeIndex索引值,即元素值就+1,然後將這個醜數存到醜數數組中,如此循環求解。
三、代碼實現
- C++代碼實現題解思路1
class Solution {
public:
bool UglyNumber(int num)
{
int flag = 0;
int count = 0;
if(num == 0)
return false;
if(num == 1)
return true;
while(num!= 1)
{
int temp = 0;
if(num%2==0)
temp = 2;
else if(num%3==0)
temp = 3;
else if(num%5==0)
temp = 5;
else
return false;
num /= temp;
}
return true;
}
int nthUglyNumber(int n)
{
int i = 0;
int count = 0; //記錄當次出現醜數是第幾次
while(count <= n)
{
if(UglyNumber(i))
{
count++;
if(count == n) //出現第n個醜數,則返回此時的醜數值i
return i;
}
i++;
}
return 0;
}
};
- C++代碼實現題解思路2
class Solution {
public:
int nthUglyNumber(int n)
{
vector<int> nums(n,1); //按順序存取每一位醜數
vector<int> ThreeIndex(3,0); //存取與2、3、5當下相乘的索引(nums中)
for(int i = 1;i<n;i++)
{
int temp1 = nums[ThreeIndex[0]]*2; //取2與其索引對應的nums中的值相乘:其中有一個就是下一個醜數
int temp2 = nums[ThreeIndex[1]]*3; //取3與其索引對應的nums中的值相乘
int temp3 = nums[ThreeIndex[2]]*5; //取5與其索引對應的nums中的值相乘
int temp = MinNumber(temp1,temp2,temp3); //三者中的最小值即爲下一個醜數
if(temp == temp1) //看哪個(2,3,5)與其當下索引對應的nums值相乘的結果是剛纔的醜數,則將索引+1
ThreeIndex[0]++; //爲什麼沒有使用if--else if--else,因爲例如2*3=6,3*2=6,所以對於這種情況,
if(temp == temp2) //2和3對應的索引都要+1
ThreeIndex[1]++; //三個索引根據if進行調整後,繼續循環,確定下一個醜數,即下一個三種temp(1\2\3)的最小值
if(temp == temp3)
ThreeIndex[2]++;
nums[i] = temp;
}
return nums[n-1];
}
int MinNumber(int a,int b,int c) //判斷三個數中的最小值
{
int flag = a < b ? a : b;
return flag < c ? flag : c;
}
};