LeetCode之Ugly Number II

/*根据提示,保存一个有序的丑数数组,然后通过不断乘以2,3,5,
从中选出最小的数作为下一个丑数。*/
class Solution {
public:
    int nthUglyNumber(int n) {
        vector uglies(1, 1);
        //uglies.reserve(n);
        int i2(0), i3(0), i5(0);
        while(uglies.size() < n){
            int p2 = 2 * uglies[i2], p3 = 3 * uglies[i3], p5 = 5 * uglies[i5];
            int res = min(p2, min(p3, p5));
            if(res == p2) ++i2;
            if(res == p3) ++i3;
            if(res == p5) ++i5;
            uglies.push_back(res);
        }
        return uglies.back();
    }
};

你可能感兴趣的:(Leetcode)