题解 | #丑数#

丑数

http://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        int factors[] = {2, 3, 5};
        unordered_set<long> hash; // 哈希表防止有重复数进入
        priority_queue<long,vector<long>, greater<long>> heap; // 小顶堆输出第n个丑叔
        hash.insert(1);
        heap.push(1);
        int ugly = 0;
        for(int i = 0; i < index; i++) {
            int cur = heap.top();
            heap.pop();
            ugly = (int)cur;
            for(auto factor:factors) {
                long x = cur * factor;
                if(!hash.count(x)){
                    hash.insert(x);
                    heap.push(x);
                }
            }
        }
        return ugly;
    }
};
全部评论

相关推荐

瑞雪兆丰年_:可以贴个超级大的校徽,以防HR眼拙
点赞 评论 收藏
分享
牛客83265014...:完了,连现在都没开始面,13号投的是不是晚了
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务