标签:color 应该 代码 return ram func dex cti etc
丑陋数字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 };
[LeetCode] 264. Ugly Number II
标签:color 应该 代码 return ram func dex cti etc
原文地址:https://www.cnblogs.com/aaronliu1991/p/11717218.html