给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。力扣原文
示例 1:
输入: n = 10
输出: 12
解释: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
示例 2:
输入: n = 1
输出: 1
解释: 1 通常被视为丑数。
解题:
var nthUglyNumber = function (n) {
let list = [1];
let p2Idx = 0,
p3Idx = 0,
p5Idx = 0;
for (let index = 1; index < n; index++) {
let result = Math.min(
list[p2Idx] * 2,
Math.min(list[p3Idx] * 3, list[p5Idx] * 5)
);
list[index] = result;
if (result === list[p2Idx] * 2) p2Idx++;
if (result === list[p3Idx] * 3) p3Idx++;
if (result === list[p5Idx] * 5) p5Idx++;
}
return list[n - 1];
};