题解 | 丑数

丑数

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param index int整型 
     * @return int整型
     */
    public int GetUglyNumber_Solution (int index) {
        // write code here
        if(index == 0){
            return 0;
        }
        int[] factors = {2,3,5};
        HashMap<Long, Integer> mp = new HashMap<>();
        // 使用小顶堆记录即将从小到大访问的丑数,保证排序
        PriorityQueue<Long> pq = new PriorityQueue<>();
        mp.put(1L,1);
        pq.offer(1L);
        long res = 0;
        for(int i = 0; i < index; i++){
            // 从小顶堆弹出最小的元素
            res = pq.poll();
            // 每一个丑数都是上一个丑数,*2、*3、*5得来的
            for(int j = 0; j < 3; j++){
                // 乘上因数
                long next = (long) res * factors[j];
                // 去重
                if(!mp.containsKey(next)){
                    mp.put(next,1);
                    pq.offer(next);
                }
            }
        }
        return (int) res;
    }
}

全部评论

相关推荐

白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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