来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii/solution/chou-shu-ii-by-leetcode/
描述
编写一个程序,找出第n个丑数。丑数就是只包含质因数 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
题解
动态规划
class Ugly {
public int[] nums = new int[1690];
Ugly() {
nums[0] = 1;
int ugly, i2 = 0, i3 = 0, i5 = 0;
for (int i = 1; i < 1690; i++) {
ugly = Math.min(Math.min(nums[i2] * 2, nums[i3] * 3), nums[i5] * 5);
nums[i] = ugly;
if (ugly == nums[i2] * 2) {
i2++;
}
if (ugly == nums[i3] * 3) {
i3++;
}
if (ugly == nums[i5] * 5) {
i5++;
}
}
}
}
class Solution {
public static Ugly u = new Ugly();
public int nthUglyNumber(int n) {
return u.nums[n - 1];
}
}
复杂度分析
- 时间复杂度:
时间检索和大约1690×5=8450次的预计算操作。
- 空间复杂度:常数空间用保存1690个丑数。