LeetCode#264 Ugly Number II (week8)

week8

題目

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, and n does not exceed 1690.
原題地址 : https://leetcode.com/problems/ugly-number-ii/description/

解析

ugly number是分解爲質數相乘形式中質數只包含2,3,5的數,要求第n大的ugly number(1屬於ugly number)。
如果從1到無窮依次檢測每個數是否爲ugly number直到找到n個,可以解決問題但是所花的代價很大,會超時。
另一種思路是ugly number都可表示爲(2^a)* (3^b) *(5^c)的形式,其中a,b,c爲自然數。
先看下面代碼:

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> v;
        v.push_back(1);
        if (n == 1) {
            return 1;
        }
        else {
            int a = 0, b = 0, c = 0;
            while (1) {
                v.push_back(min(v[a] * 2, v[b] * 3, v[c] * 5));
                if (v.size() == n) {
                    return v.back();
                }
                if (v.back() == v[a] * 2) {
                    ++a;
                }
                if (v.back() == v[b] * 3) {
                    ++b;
                }
                if (v.back() == v[c] * 5) {
                    ++c;
                }
            }
        }
    }
    int min(int a, int b, int c) {
        int result = a;
        if (result > b) {
            result = b;
        }
        if (result > c) {
            result = c;
        }
        return result;
    }
};

代碼解析

取3個起指針作用的數(如a,b,c),起始都爲0。數組(命名爲v)起始只有元素1(第一個ugly number),後面的ugly number都是對前面已知的某個ugly number乘2或乘3或乘5得到,此時三個指針都指向v[0],因爲v[a]*2=2,v[b] *3=3,v[c] *5=5,因此取2作爲下一個ugly number,此時對能取得該ugly number的指針加1,即a。重複操作,考慮已知數組爲1,2,3,此時a=1, v[a]=2 ; b=1, v[b]=2 ; c=0, v[c]=1,重複步驟,因爲v[a] *2=4 , v[c] *5= 5,因此取4,加a。對能取得該ugly number的指針加1能防止如添加10(2 *5或5 *2)時只自增a或c而忽略另一個的問題。重複直至數組大小爲n,此時數組最後一個元素即爲所求。

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