-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode264.js
60 lines (50 loc) · 1.17 KB
/
leetcode264.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @param {number} n
* @return {number}
* prime factor of only 2, 3, 5;
* https://leetcode.com/submissions/detail/569788511/
*/
var nthUglyNumber = function (n) {
let nums = {
2: 0,
3: 0,
5: 0,
};
let arr = [1];
if (n < 2) return 1;
while (arr.length != n) {
let min = Infinity;
let theKey = undefined;
for (let key in nums) {
if (key * arr[nums[key]] < min) {
min = key * arr[nums[key]];
theKey = key;
}
}
nums[theKey] += 1;
if (!arr.includes(min)) arr.push(min);
}
return arr.pop();
};
var nthUglyNumber2 = function (n) {
let nums = {
2: 0,
3: 0,
5: 0,
};
let arr = [1];
if (n < 2) return 1;
while (arr.length != n) {
let keys = [];
// get the min by trying out all choices in nums
let min = Math.min(...Object.keys(nums).map(key => key * arr[nums[key]]));
// if that choice of key result a min value, then add to keys arr
for (let key in nums) {
if (key * arr[nums[key]] === min) keys.push(key);
}
// increment value by 1 where value represents index in arr;
keys.forEach(k => (nums[k] += 1));
arr.push(min);
}
return arr.pop();
};