我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/chou-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 题解
- 本题使用空间换时间,dp[i]=MIM(dp[a],dp[b],dp[c]),
a指向2的倍数,b指向3的倍数,c指向5的倍数. - 为什么while<n-1,而不是while<n,因为要从dp[1]开始算起,若是<n,最后一个urlyNum指向的是n-1,dp[++urlyNum]是dp[n],越界
- 为什么while里面要套while.23=32,可以自己举例子试试,当这两个相等时,加入选中a++,则下一轮 b*2=6<当前丑数.
2. 代码
class Solution {
// 210 丑数
public int nthUglyNumber(int n) {
int[] res=new int[n];
res[0]=1;
int point2=0; //指向2的倍数的指针
int point3=0;
int point5=0;
int uglyNum=0;// 当前最大丑数下标
while (uglyNum<n-1){
while (res[point2]*2<=res[uglyNum]){
point2++;
}
while (res[point3]*3<=res[uglyNum]){
point3++;
}
while (res[point5]*5<=res[uglyNum]){
point5++;
}
int candidate2=res[point2]*2;
int candidate3=res[point3]*3;
int candidate5=res[point5]*5;
res[++uglyNum]=Math.min(Math.min(candidate2,candidate3),candidate5);
if (res[uglyNum]==candidate2){
point2++;
}else if (res[uglyNum]==candidate3){
point3++;
}else{
point5++;
}
}
return res[n-1];
}
}