题目链接: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. 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.
思路:
是super ugly number的特殊情况。解法相同。
算法:
public int nthUglyNumber(int n) {
int res[]=new int[n];
int idx[]=new int[3];
int primes[]=new int[]{2,3,5};
res[0] = 1;
for (int i = 1; i < n; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < primes.length; j++) {
min = Math.min(min, primes[j] * res[idx[j]]);
}
res[i] = min;
for (int k = 0; k < primes.length; k++) {
if (min == res[idx[k]] * primes[k]) {
idx[k]++;
}
}
}
return res[n - 1];
}
时间: 2024-11-05 17:33:39