264. Ugly Number II

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, and n does not exceed 1690.

解法1:

C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
public int nthUglyNumber(int n) {
int[] dp = new int[n];
dp[0] = 1;
int i = 0, j = 0, k = 0;
int d1 = 2, d2 = 3, d3 = 5;
int count = 1;
for (int p = 1; p < n; p++) {
int res = Math.min(Math.min(d1, d2), d3);
dp[p] = res;
if (d1 == res) {
d1 = 2 * dp[++i];
}
if (d2 == res) {
d2 = 3 * dp[++j];
}
if (d3 == res) {
d3 = 5 * dp[++k];
}
}
return dp[n - 1];
}
}