方法一:最小堆
初始化一个空堆,先将最小丑数1放入优先队列(堆顶元素最小),取出堆顶元素x(最小),将2x,3x,5x压入堆,使用set进行去重操作,2x,3x,5x在set中不存在时,将值压入priorityQueue,和set,第n次取的是第n个丑数。
class Solution {
public int nthUglyNumber(int n) {
PriorityQueue<Long> heap = new PriorityQueue<Long>();
HashSet<Long> set = new HashSet<>();
heap.add(1L);
set.add(1L);
long nthUgly = 0L;
for(int i=1;i<=n;i++){
nthUgly = heap.poll();
Long x2 = nthUgly*2;
Long x3 = nthUgly*3;
Long x5 = nthUgly*5;
if(!set.contains(x2)){
set.add(x2);
heap.add(x2);
}
if(!set.contains(x3)){
set.add(x3);
heap.add(x3);
}
if(!set.contains(x5)){
set.add(x5);
heap.add(x5);
}
}
return (int)nthUgly;
}
}
class Solution {
public int nthUglyNumber(int n) {
int a=0,b=0,c=0;
int[] dp = new int[n];
dp[0] = 1;
for(int i=1;i<n;i++){
dp[i] = Math.min(Math.min(dp[a]*2,dp[b]*3),dp[c]*5);
//那个数被用那个++,其余不动
if(dp[i]==dp[a]*2) a++;
if(dp[i]==dp[b]*3) b++;
if(dp[i]==dp[c]*5) c++;
}
return dp[n-1];
}
}