丑陋数字II。题目问的是求出第N个丑陋数字。思路是需要按规则求出前N-1个丑陋数字才行。代码有点像DP但又不是DP,应该比较直观。
时间O(n)
空间O(n)
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var nthUglyNumber = function(n) { 6 let nums = new Array(n); 7 let index2 = 0, 8 index3 = 0, 9 index5 = 0; 10 nums[0] = 1; 11 for (let i = 1; i < n; i++) { 12 nums[i] = Math.min(nums[index2] * 2, Math.min(nums[index3] * 3, nums[index5] * 5)); 13 if (nums[i] === nums[index2] * 2) index2++; 14 if (nums[i] === nums[index3] * 3) index3++; 15 if (nums[i] === nums[index5] * 5) index5++; 16 } 17 return nums[n - 1]; 18 };