-
Notifications
You must be signed in to change notification settings - Fork 887
/
SuperUglyNumber.swift
47 lines (37 loc) · 1.24 KB
/
SuperUglyNumber.swift
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
/**
* Question Link: https://leetcode.com/problems/super-ugly-number/
* Primary idea: Use dict to track indices to build a helper array,
* remember to kill duplicates
* Time Complexity: O(n^2), Space Complexity: O(n)
*
*/
class SuperUglyNumber {
func nthSuperUglyNumber(n: Int, _ primes: [Int]) -> Int {
var uglyNums = [Int](count: n, repeatedValue: 1)
var dict = _init(primes)
for i in 1..<n {
uglyNums[i] = _getMin(&dict, uglyNums, i - 1)
}
return uglyNums[n - 1]
}
private func _init(primes: [Int]) -> [Int: Int] {
var dict = [Int: Int]()
for prime in primes {
dict[prime] = 0
}
return dict
}
private func _getMin(inout dict: [Int: Int], _ uglyNums: [Int], _ previous: Int) -> Int {
var minNum = Int.max
for prime in dict.keys {
var current = uglyNums[dict[prime]!] * prime
// kill duplicates
if current == uglyNums[previous] {
dict[prime]! += 1
current = uglyNums[dict[prime]!] * prime
}
minNum = min(current, minNum)
}
return minNum
}
}