题解 | #丑数#

丑数

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;
    }
};
全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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