剑指Offer——丑数

Question

把只包含因子2、3和5的数称作丑数。

Solution

用空间换时间。保存之前生成的丑数,因为之后生成的丑数都是之前的丑数乘上2,3或5得到的。而且只需要,乘上2,3,5以后比当前最大值大的最小值。因此,我们可以标记乘上2,3,5,刚好比最大值大的位置。

Code

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
    	vector<int> vec(index, 0);
        vec[0] = 1;
        int p2 = 0;
        int p3 = 0;
        int p5 = 0;
        int p = 1;
        while (p < index) {
            int minValue = min(vec[p5] * 5, min(vec[p2] * 2, vec[p3] * 3));
            vec[p] = minValue;
            while (vec[p2] * 2 <= vec[p])
                p2++;
            while (vec[p3] * 3 <= vec[p])
                p3++;
            while (vec[p5] * 5 <= vec[p])
                p5++;
            p++;
        }
        return vec[index - 1];
    }
};
posted @ 2017-11-02 14:29  清水汪汪  阅读(153)  评论(0编辑  收藏  举报