编写一个程序,找出第 n 个丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
题目链接 : https://leetcode-cn.com/problems/ugly-number-ii
解题思路:
任意一个丑数一定是另一个丑数乘以2或3或5得到的,我们可以使用一个数组将已经确认为丑数的数按照从小到大的顺序记录下来,每个丑数都是前面的丑数乘以2、3或5得来的。
如何确保数组中的丑数是排好序的?假设数组中已经有若干个排好序的丑数,并且其中最大的丑数为M。那么下一个丑数一定是数组中某个数乘以2或3或5的结果,所以我们把数组中的每个数都乘以2,找到第一个大于M的结果M2(小于等于M的结果肯定已经在数组中了,不需要考虑);同理,把数组中的每个数都乘以3,找到第一个大于M的结果M3;把数组中的每个数都乘以5,找到第一个大于M的结果M5。那么下一个丑数一定是M2、M3、M5当中的最小值。
实际上,在寻找M2、M3、M5的过程中,不需要每次都从头开始遍历,只要记住上一次遍历到的位置,继续往后遍历即可。
参考: https://blog.youkuaiyun.com/qq_34342154/article/details/78768201
class Solution {
public static int min(int a, int b, int c) {
int temp = a < b ? a : b;
return temp < c ? temp : c;
}
public int nthUglyNumber(int n) {
if (n == 0)
return 0;
int[] arr = new int[n];
arr[0] = 1;
int count = 1;
int index2 = 0;
int index3 = 0;
int index5 = 0;
while (count < n) {
int min = min(arr[index2] * 2, arr[index3] * 3, arr[index5] * 5);
arr[count] = min;
while (arr[index2] * 2 <= arr[count])
index2++;
while (arr[index3] * 3 <= arr[count])
index3++;
while (arr[index5] * 5 <= arr[count])
index5++;
++count;
}
return arr[n - 1];
}
}