1. 程式人生 > >【劍指offer】49、醜數

【劍指offer】49、醜數

一個 醜數 for 超級 class off 指針 number pub

題目

把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

思路

顯然每個數判斷不可取,計算量超級大。

我們要用前面的醜數來生成後面的醜數

從1開始,記三個指針t1,t2,t3,都指向1。

每次將t1,t2,t3所指數字分別乘上2,3,5,取最小的一個生成下一個醜數,並且將對應指針指向新生成的醜數

反復操作即可

(實際代碼過程中,使用索引代替指針)

class Solution {
public:
    int GetUglyNumber_Solution(int
index) { if (index < 7) return index; vector<int> res(index); res[0] = 1; int t2 = 0, t3 = 0, t5 = 0, i; for (i = 1; i < index; ++i) { res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5)); if (res[i] == res[t2] * 2
) t2++; if (res[i] == res[t3] * 3) t3++; if (res[i] == res[t5] * 5) t5++; } return res[index - 1]; } };

【劍指offer】49、醜數