264. 丑数 II 中等 最小堆+哈希表去重 动态规划

  1. 丑数 II
    给你一个整数 n ,请你找出并返回第 n 个 丑数 。

丑数 就是只包含质因数 2、3 和/或 5 的正整数。

示例 1:

输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
示例 2:

输入:n = 1
输出:1
解释:1 通常被视为丑数。

提示:

1 <= n <= 1690

动态规划O(n)
class Solution {
    
    public int nthUglyNumber(int n) {
        int f[]=new int [n+1];
        f[1]=1;
        int p2=1,p3=1,p5=1;
        for(int i=2;i<=n;++i){
        	int x2=f[p2]*2,x3=f[p3]*3,x5=f[p5]*5;
        	f[i]=Math.min(Math.min(x2, x3), x5);
        	if(f[i]==x2)p2++;//不能用else因为可能同时几个都符合,比如6=2*3,都需要修改指针
        	if(f[i]==x3)p3++;
        	if(f[i]==x5)p5++;
        }
        return f[n];
    }
}
最小堆+哈希去重
import java.util.*;

class Solution {
    
    public int nthUglyNumber(int n) {
        PriorityQueue<Long> q=new PriorityQueue<>();
        Set<Long> st=new HashSet<>();
        q.offer(1l);
        while((n--)>1){
        	long t=q.poll();
        	if(!st.contains(t*2)){
        		q.offer(t*2);
        		st.add(t*2);
        	}
        	if(!st.contains(t*3)){
        		q.offer(t*3);
        		st.add(t*3);
        	}
        	if(!st.contains(t*5)){
        		q.offer(t*5);
        		st.add(t*5);
        	}
        }
        return q.peek().intValue();
    }
}
posted @ 2022-11-17 23:01  林动  阅读(15)  评论(0编辑  收藏  举报