class Solution {
//最小堆解法
//最小堆的定义:根节点的值比左右结点的值要小(父节点的值比左右孩子结点的值要小)
public int nthUglyNumber(int n) {
//质因数
int[] factors = {2,3,5};
//定义丑数
int ugly = 0;
//用一个set来取出重复的结果集
//将最小堆的根节点存入set中(包括去重),这样,遍历set取出的第n个数就是从小到大的第n个丑数
Set<Long> set = new HashSet<>();
//定义一个最小堆,jdk中使用PriorityQueue来定义堆
PriorityQueue<Long> heap = new PriorityQueue<>();
//将丑数1初始化
set.add(1L);
heap.offer(1L);
//使用最小堆来获取堆的根来作为最小的丑数
for(int i =0;i<n;i++){
long curr = heap.poll();
ugly = (int)curr;
for(int factor : factors){
long next = curr * factor;
if(set.add(next)) {
heap.offer(next);
}
}
}
return ugly;
}
}
算法训练|丑数(最小堆)
最新推荐文章于 2022-04-18 11:42:34 发布