zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    html+css动态篇
    html+css定位篇
    首页的css
    display详细说明
    html+css 布局篇
    html+css杂记
    JS与ES的关系
    H5本地存储
    JavaScript面向对象
    JavaScript执行上下文
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14888921.html
Copyright © 2011-2022 走看看