【LeetCode】264. Ugly Number II 丑数 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
- 1 is typically treated as an ugly number.
- n does not exceed 1690.
题目大意
编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 5 的正整数。
解题方法
- 要计算第几个其实就是从 1 开始然后分别乘以 2,3,5 取其中的最小值也就是 2 放在第二个,
- 然后 2 分别乘以 2,3,5 取最小的,还要和上一次 1 乘以 2,3,5 取最小的(这里 2 可以不用乘了,已经乘过了),也就是 3 ;简化一下就是 1 * 3, 1 * 5, 2 * 2 (因为 3 和 5 比 2 大,所以就不需要2,3,5都乘一遍了)取最小
- 然后 1,2,3 分别乘以 2,3,5 取最小的(要排除 2 和 3),4 ;简化一下就是 1 * 5, 2 * 2, 2 * 3
- 可以看到其实就是乘以 2,3,5 的位置每次都是进一,然后分别和相应的位置相乘,取最小值
- note: 如果 2 * 5 这种,2 和 5 的位置都需要 +1,因为也可以是 5 * 2
class Solution {
public int nthUglyNumber(int n) {
int[] dp = new int[n];
dp[0] = 1;
int two = 0;
int three = 0;
int five = 0;
for (int i = 1; i < n; i++) {
dp[i] = Math.min(dp[two] * 2, Math.min(dp[three] * 3, dp[five] * 5));
if (dp[i] == dp[two] * 2) {
two++;
}
if (dp[i] == dp[three] * 3) {
three++;
}
if (dp[i] == dp[five] * 5) {
five++;
}
}
return dp[n - 1];
}
}
执行耗时:3 ms,击败了81.85% 的Java用户
内存消耗:37.6 MB,击败了44.61% 的Java用户
