leecode 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class  {
public int nthUglyNumber(int n) {
int dp[] = new int[n];
dp[0] = 1;

int index2 = 0;
int index3 = 0;
int index5 = 0;

int fact2 = 2;
int fact3 = 3;
int fact5 = 5;

for(int i=1; i<n; i++){

dp[i] = Math.min(Math.min(fact2, fact3), fact5);
if(dp[i] == fact2){
index2 ++;
fact2 = dp[index2] * 2;
}
if(dp[i] == fact3){
index3 ++;
fact3 = dp[index3] * 3;
}
if(dp[i] == fact5){
index5 ++;
fact5 = dp[index5] * 5;
}
}
return dp[n-1];
}
}
  • 为每一个factor设定一个记录
  • 由于只能被2 3 5 整除,每次取每个factor对应的index所对应的位置相乘