给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
示例 1:
输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
解题思路
维护一个最小堆和一个set,记录以及进入堆的丑数,每次将堆的最小值出队,并且将它的2,3,5倍数入队
代码
class Solution {public int nthUglyNumber(int n) {PriorityQueue<Long> priorityQueue=new PriorityQueue<>();Set<Long> set=new HashSet<>();priorityQueue.add(1L);int cnt=0;while (true){long cur=priorityQueue.poll();cnt++;if(cnt==n)return (int)cur;if(!set.contains(cur*2)){priorityQueue.add(cur*2); set.add(cur*2);}if(!set.contains(cur*3)){priorityQueue.add(cur*3);set.add(cur*3);}if(!set.contains(cur*5)){priorityQueue.add(cur*5);set.add(cur*5);}}}
}