0264. Ugly Number Ⅱ (M)
Ugly Number II (M)
题目
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
题意
找到第n个因数只有2、3、5的整数。
思路
- 自底向上生成第n个丑陋数:每个丑陋数都可以由之前的某一个丑陋数乘2或3或5得到。因此记录下2、3、5要乘的下一个丑陋数的下标,每一次从得到的三个数中选取最小的一个作为新的丑陋数加入列表中,并根据这个值将2、3、5要乘的下一个下标往后挪一位。如下图示例:
- 堆:用小顶堆存储丑陋数,每次取堆顶的数x作为最新的丑陋数,并将所有与x相同的数除去,最后再往堆里存入2x、3x、5x。重复操作n次后得到的就是第n个丑陋数。(注意这种方法每次都是用最新的丑陋数去乘2、3、5,因此可能出现int越界的情况,所以堆必须用long)
代码实现
Java
迭代
class Solution {
public int nthUglyNumber(int n) {
List<Integer> list = new ArrayList<>();
list.add(1);
int times2pos = 0, times3pos = 0, times5pos = 0;
while (list.size() < n) {
int times2 = list.get(times2pos) * 2;
int times3 = list.get(times3pos) * 3;
int times5 = list.get(times5pos) * 5;
int min = Math.min(Math.min(times2, times3), times5);
if (min == times2) times2pos++;
if (min == times3) times3pos++;
if (min == times5) times5pos++;
list.add(min);
}
return list.get(list.size() - 1);
}
}
堆
class Solution {
public int nthUglyNumber(int n) {
Queue<Long> heap = new PriorityQueue<>();
heap.offer(1l);
int count = 0;
long ans = 0;
while (count != n) {
ans = heap.poll();
while (!heap.isEmpty() && heap.peek() == ans) {
heap.poll();
}
heap.offer(ans * 2);
heap.offer(ans * 3);
heap.offer(ans * 5);
count++;
}
return (int)ans;
}
}
JavaScript
/**
* @param {number} n
* @return {number}
*/
var nthUglyNumber = function (n) {
let list = [1]
let pos2 = 0, pos3 = 0, pos5 = 0
while (list.length < n) {
let times2 = list[pos2] * 2
let times3 = list[pos3] * 3
let times5 = list[pos5] * 5
let min = Math.min(times2, times3, times5)
if (min === times2) pos2++
if (min === times3) pos3++
if (min === times5) pos5++
list.push(min)
}
return list[n - 1]
}
参考