Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

O(n log n) time O(n) space Heap solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int nthUglyNumber(int n) {
if (n <= 0) return 0;
PriorityQueue<Long> pq = new PriorityQueue<>();
long res = 1l;
pq.offer(res);
for (int i = 1; i <= n; i++) {
res = pq.poll();
while (!pq.isEmpty() && res == pq.peek()) {
pq.poll();
}
pq.offer(res * 2);
pq.offer(res * 3);
pq.offer(res * 5);
}
return (int) res;
}
}

O(n) time O(n) space DP solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int nthUglyNumber(int n) {
if (n <= 0) return 0;
int[] res = new int[n];
res[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;
for (int i = 1; i < n; i++) {
int ugly = Math.min(Math.min(res[index2] * 2, res[index3] * 3), res[index5] * 5);
res[i] = ugly;
if (res[index2] * 2 == ugly)
index2++;
if (res[index3] * 3 == ugly)
index3++;
if (res[index5] * 5 == ugly)
index5++;
}
return res[n - 1];
}
}