264. 丑数 II

解法一:小根堆

要得到从小到大的第 (n) 个丑数,可以使用最小堆实现。

初始时堆为空。首先将最小的丑数 (1) 加入堆。

每次取出堆顶元素 (x),则 (x) 是堆中最小的丑数,由于 (2x, 3x, 5x) 也是丑数,因此将 (2x, 3x, 5x) 加入堆。

上述做法会导致堆中出现重复元素的情况。为了避免重复元素,可以使用哈希集合去重,避免相同元素多次加入堆。

在排除重复元素的情况下,第 (n) 次从最小堆中取出的元素即为第 (n) 个丑数。

typedef long long LL;

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> factors = {2, 3, 5};
        priority_queue<LL, vector<LL>, greater<LL>> heap;
        unordered_set<LL> S;
        heap.push(1);
        S.insert(1);

        int res = 1;
        for(int i = 0; i < n; i++)
        {
            LL t = heap.top();
            heap.pop();

            res = t;
            for(int factor : factors)
            {
                LL x = t * factor;
                if(S.count(x) == 0)
                {
                    S.insert(x);
                    heap.push(x);
                }
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/fxh0707/p/14888921.html