题目: 只包含因子2、3、5的数为丑数。求第1500个丑数
给你一个整数 n ,请你找出并返回第 n 个 丑数 。
说明:丑数是只包含质因数 2、3 和/或 5 的正整数;1 是丑数。
示例 1:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
方式一:暴力-容易超时
public class Main49 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
System.out.println(kthulgy(k, new ArrayList<Integer>()));
}
private static int kthulgy(int k, List<Integer> list) {
if (k <= 0)
return -1;
list.add(1);
int temp = 2;//2-无穷的找,直到找够k个
while (list.size() != k){
int value = temp;
while (value % 2 == 0){//10,5 ;14 7
value /= 2;
}
while (value % 3 == 0){
value /= 3;
}
while (value % 5 == 0){//1
value /=5 ;
}
if (value == 1){//1 ; 7
list.add(temp);
}
++temp;
}
return list.get(k-1);
}
}
方式二: 优先队列-小顶堆
class Solution {
public int nthUglyNumber(int n) {
Queue<Long> queue = new PriorityQueue<>();
Set<Long> set = new HashSet<>();
int[] factorArr = { 2, 3, 5 };
queue.add(1L);
set.add(1L);
Long res = 1L;
for (int i = 1; i <= n; i++) {
res = queue.poll();
for (int factor : factorArr) {
Long next = res * factor;
if (set.contains(next)) {
continue;
}
queue.add(next);
set.add(next);
}
}
return res.intValue();
}
}