0
点赞
收藏
分享

微信扫一扫

【LeetCode剑指offer49】丑数(小顶堆或DP)

祈澈菇凉 2022-02-05 阅读 32

一、题目

在这里插入图片描述

二、思路

求前k大经常用到优先级队列,小顶堆,循环将符合要求的丑数加入小顶堆,取k次堆顶元素即可让堆顶为第k个丑数。而逐个加入丑数即加入 2 x 2x 2x 3 x 3x 3x 5 x 5x 5x进入集合(去重)即可。注意这里加入小顶堆的元素不能是int类型,否则会报错overflow(因为next = temp * factor后可能会越界):

Line 17: Char 33: runtime error: signed integer overflow: 429981696 * 5 cannot be represented in type 'int' (solution.cpp)

三、代码

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> fac = {2, 3, 5};
        //用int还不够
        unordered_set<long>s;
        //小顶堆用greater
        priority_queue<long, vector<long>, greater<long>>min_heap;
        s.insert(1L);
        min_heap.push(1L);
        int ugly = 0;
        for(int i = 0; i < n; i++){
            long temp = min_heap.top();
            min_heap.pop();
            ugly = (int)temp;
            for(int factor: fac){
                long next = temp * factor;
                if(!s.count(next)){
                    s.insert(next);
                    min_heap.push(next);
                }       
            }
        }
        return ugly;
    }
};
举报

相关推荐

0 条评论