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的整数。
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;
}
}
/**
* @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]
}
参考
[LeetCode] 264. Ugly Number II 丑陋数之二
原文:https://www.cnblogs.com/mapoos/p/13237461.html