其他分享
首页 > 其他分享> > 剑指Offer 49.丑数

剑指Offer 49.丑数

作者:互联网

在这里插入图片描述

https://leetcode-cn.com/problems/chou-shu-lcof/solution/chou-shu-by-leetcode-solution-0e5i/

小根堆,注意小根堆的定义方式

在这里插入图片描述

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> factors = {2, 3, 5};
        unordered_set<long> seen;
        priority_queue<long, vector<long>, greater<long>> heap;
        seen.insert(1L);//将1转换为long型
        heap.push(1L);
        int ugly = 0;
        for (int i = 0; i < n; i++) {
            long curr = heap.top();
            heap.pop();
            ugly = (int)curr;
            for (int factor : factors) {
                long next = curr * factor;
                if (!seen.count(next)) {
                    seen.insert(next);
                    heap.push(next);
                }
            }
        }
        return ugly;
    }
};

标签:丑数,curr,Offer,int,49,long,next,heap,seen
来源: https://blog.csdn.net/qq_41191468/article/details/120276216