[LeetCode] Ugly Number II

Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

解題思路:

題意說找到第n個Ugly Number。一個naive的辦法是驗證每個數,直到第n個醜數產生爲止。但是這樣可能會產生超時錯誤。

一個比較好的辦法就是直接產生醜數,然後計數即可。如何找到下一個醜數呢?這個規律還真不好找。網上查閱了一些資料,才弄懂。

1*2,2*2,3*2,4*2,5*2,6*2,8*2… 
1*3,2*3,3*3,4*3,5*3,6*3,8*3… 
1*5,2*5,3*5,4*5,5*5,6*5,8*5… 

醜數列表可以按上面排列。注意,可能會有重複的,比如3*2和2*3。對於下一個醜數,都是將某個已有醜數乘以2或3或5,每一行都是順序的醜數*相應的質,因此需要一個數組來記錄已經出現過的醜數。將所有醜數分成三組(可能一個醜數分到多個組中 ),記錄當前醜數的下標,然後選取下一個最小的醜數即可。注意這裏不是else if,因爲每個醜數可以分配到多個組中。

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> result(n, 0);
        int index2 = 0, index3 = 0, index5 = 0;
        result[0] = 1;
        for(int i = 1; i < n; i++){
            result[i] = min(min(result[index2] * 2, result[index3] * 3), result[index5] * 5);
            if(result[i] == result[index2] * 2) index2++;
            if(result[i] == result[index3] * 3) index3++;
            if(result[i] == result[index5] * 5) index5++;
        }
        return result[n-1];
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章