Skip to content

Commit d1a99ed

Browse files
committed
Add solution #264
1 parent be35db0 commit d1a99ed

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

solutions/0264-ugly-number-ii.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* 264. Ugly Number II
3+
* https://leetcode.com/problems/ugly-number-ii/
4+
* Difficulty: Medium
5+
*
6+
* Write a program to find the n-th ugly number.
7+
*
8+
* Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
9+
*/
10+
11+
/**
12+
* @param {number} n
13+
* @return {number}
14+
*/
15+
var nthUglyNumber = function(n, factors = [2, 3, 5], offsets = [0, 0, 0]) {
16+
const numbers = [1];
17+
while (numbers.length < n) {
18+
const candidates = factors.map((v, i) => numbers[offsets[i]] * v);
19+
const target = Math.min(...candidates);
20+
candidates.forEach((c, i) => target === c ? offsets[i]++ : null);
21+
numbers.push(target)
22+
}
23+
return numbers[n - 1];
24+
};

0 commit comments

Comments
 (0)