题目:
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
- 1 是丑数。
- n 不超过1690。
注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/
解法1:heap
/**
* 思路:
* 丑数:从1开始,当前的数*235,插入堆中,之后删除堆顶元素加入到result中
* 在用堆顶元素*235,将新的丑数加入到堆中,并用set集合去重。循环这个过程
*/
public int nthUglyNumber(int n) {
PriorityQueue<Long> heap = new PriorityQueue<>();
heap.add(1L);
long[] res = new long[n + 1];
int[] primes={
2,3,5};
HashSet<Long> set = new HashSet<>();
int index=1;
while (!heap.isEmpty()) {
Long remove = heap.remove();
for (int prime : primes) {
long uglyNum = remove * prime;
if (!set.contains(uglyNum)) {
set.add(uglyNum);
heap.add(uglyNum);
}
}
res[index++] = remove;
if (index == res.length) return (int)res[n];
}
return (int)res[n];
}
时间复杂度:On
空间复杂度:On