
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.
Hint:
维持一个数组,依次存入丑数序列。
public int nthUglyNumber(int n) {
int[] nums = new int[n];
nums[0] = 1;
int i = 0, j = 0, k = 0, t = 1;
while (t < n) {
int min = Math.min(Math.min(nums[i] * 2, nums[j] * 3), nums[k] * 5);
nums[t++] = min;
if (nums[i] * 2 == min) {
i++;
}
if (nums[j] * 3 == min) {
j++;
}
if (nums[k] * 5 == min) {
k++;
}
}
return nums[n - 1];
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。