我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:1 是丑数。
n 不超过1690。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/chou-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
一道经典ACM题目。
将丑数打表,然后求解即可。
打表思路:
丑数*2 = 新的丑数a
丑数*3 = 新的丑数b
丑数*5 = 新的丑数c
为了表格里面的丑数从小到大排序,需要从三个丑数中取最小的丑数,然后插入数组,然后将2或3或5的位置计数+1。
class Solution {
static final int SIZE = 1691;
static int record[] = new int[SIZE];
public static void init() {
if(record[0] == 1)
return;
record[0] = 1;
int i=1;
int indexTwo = 0;
int indexThree = 0;
int indexFive = 0;
while(i<SIZE) {
int resTwo = record[indexTwo] * 2;
int resThree = record[indexThree] * 3;
int resFive = record[indexFive] * 5;
int minRes = Math.min(Math.min(resTwo, resThree), resFive);
if(minRes == resTwo)
indexTwo ++;
if(minRes == resThree)
indexThree++;
if(minRes == resFive)
indexFive++;
record[i] = minRes;
i++;
}
}
public int nthUglyNumber(int n) {
init();
return record[n-1];
}
}