264.丑数II
class Solution {
int[] nums = new int[]{2, 3, 5};
public int nthUglyNumber(int n) {
Queue<Long> q = new PriorityQueue<>();
Set<Long> s = new HashSet<>();
q.add(1L);
s.add(1L);
for (int i = 1; i <= n; i++) {
long x = q.poll();
if (i == n) return (int) x;
for (int num : nums) {
if (!s.contains(num * x)) {
s.add(num * x);
q.add(num * x);
}
}
}
return -1;
}
}
优先队列(小根堆)解法
起始先将最小丑数 1 放入队列
每次从队列取出最小值 x,然后将 xx 所对应的丑数 2x、3x 和 5x进行入队。
对步骤 2 循环多次,第 n 次出队的值即是答案。
为了防止同一丑数多次进队,我们需要使用数据结构 Set 来记录入过队列的丑数。
313.超级丑数
题目意思::数组里给的都是质数,将这些质数进行各种组合乘起来(每个质数可以不用也可用多次),将结果进行排序,把第n个数返回
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
Set<Long> s = new HashSet<>();
Queue<Long> q = new PriorityQueue<>();
s.add(1L);
q.add(1L);
while (n-- > 0) {
long x = q.poll();
if(n==0) return (int) x;
for (int i : primes) {
if (!s.contains(i * x)) {
s.add(i * x);
q.add(i * x);
}
}
}
return -1;
}
}