Problem 264

Posted by Ruizhi Ma on October 26, 2020

Solution URL

https://leetcode.com/submissions/detail/413543446/

代码

class Solution {
    public int nthUglyNumber(int n) {
        //https://leetcode-cn.com/problems/ugly-number-ii/solution/zui-rong-yi-li-jie-de-si-lu-by-linzb-2/
        int[] ele = new int[]{2,3,5};
        long[] res = new long[n];
        res[0] = 1;
        PriorityQueue<Long> pq = new PriorityQueue<>();

        for(int i = 0; i < res.length; i++){
            for(int j = 0; j < ele.length; j++){
                if(!pq.contains((long)res[i] * ele[j])){
                    pq.add((long)res[i] * ele[j]);
                }
            }

            //将优先队列头元素加入res结果集中
            if(i + 1 < res.length){
                res[i + 1] = pq.poll();
            }
        }

        return (int)res[n - 1];
    }
}