编写一个程序,找出第 n
个丑数。
丑数就是质因数只包含 2, 3, 5
的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
是前 10 个丑数。
说明:
1
是丑数。n
不超过1690。
我的第一想法是先写一个函数判断这个数是否是丑数,然后通过一个for循环判断每个数是否是丑数,直到丑数的数量达到n。
unfortunately,超时了。下面是超时代码:
class Solution {
public int nthUglyNumber(int n) {//找出第n个丑数
int m=0;
for(int i=1 ;i<100000000;i++){
if(isUgly(i) == true)
m++;
if(m == n)
return i;
}
return 0;
}
public boolean isUgly(int num){
if(num < 1)
return false;
while(num % 2 ==0) num /= 2;
while(num % 3 ==0) num /= 3;
while(num % 5 ==0) num /= 5;
return num ==1;
}
}
法二:三指针法,看了题解才知道怎么做。上面的方法之所以会超时,是因为我们把每个数都判断了一遍,不管这个数是不是丑数。因为这个方法只计算丑数,从而大大提升了时间效率。开辟一个长度为 n 的数组来进行动态规划过程:
首先我们要发现,任何一个丑数,都是可以由其前面的某个丑数乘2,或乘3,或乘5得到。
建立一个长度为 n 的 dp 数组,dp[0]表示第一个丑数,即dp[0]=1,dp[i] 表示第 i + 1 个丑数。
然后设立三个变量:two, three, five,初始值都为0,它们都代表 dp 数组中的索引。我们通过选取 dp[two] * 2, dp[three] * 3 和 dp[five] * 5 中的最小值来确定下一个丑数的值。
当找到了下一个丑数后,假如这个丑数是由 two 得来的,我们就 two++;假如是由 three 得来的,我们就 three++;是由 five 得来的,我们就 five++。这样就可以保证每个丑数都会被找出来。
class Solution {
public int nthUglyNumber(int n) {
int[] dp = new int [n];
dp[0] = 1;
int two=0,three=0,five=0;
for(int i=1; i< n;i++){
int t1 = dp[two] * 2;
int t2 = dp[three] * 3;
int t3 = dp[five] * 5;
dp[i] = Math.min(Math.min(t1,t2),t3);
if(dp[i] == t1) two++;
if(dp[i] == t2) three++;
if(dp[i] == t3) five++;
}
return dp[n-1];
}
}
//遍历过程
i=1
t1 = dp[0] * 2 -> 2
t2 = dp[0] * 3 -> 3
t3 = dp[0] * 5 -> 5
min(2,3,5) -> 2 -> dp[1] = 2 -> two + 1 = 1
i=2
t1 = dp[1] * 2 -> 4
t2 = dp[0] * 3 -> 3
t3 = dp[0] * 5 -> 5
min(4,3,5) -> 3 -> dp[2] = 3 -> three + 1 = 1
i=3
t1 = dp[1] * 2 -> 4
t2 = dp[1] * 3 -> 6
t3 = dp[0] * 5 -> 5
min(4,6,5) -> 4 -> dp[3] = 4 -> two + 1 = 2