Skip to content

Commit 8fbe73d

Browse files
authored
feat: add swift implementation to lcci problem: No.17.09 (doocs#2781)
1 parent 0c1e43d commit 8fbe73d

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

lcci/17.09.Get Kth Magic Number/README.md

+26
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,32 @@ int getKthMagicNumber(int k) {
196196
}
197197
```
198198
199+
```swift
200+
class Solution {
201+
private let factors = [3, 5, 7]
202+
203+
func getKthMagicNumber(_ k: Int) -> Int {
204+
var heap: [Int] = [1]
205+
var seen = Set<Int>()
206+
seen.insert(1)
207+
208+
var value = 1
209+
for _ in 1...k {
210+
value = heap.removeFirst()
211+
for factor in factors {
212+
let nextValue = value * factor
213+
if !seen.contains(nextValue) {
214+
heap.append(nextValue)
215+
seen.insert(nextValue)
216+
}
217+
}
218+
heap.sort()
219+
}
220+
return value
221+
}
222+
}
223+
```
224+
199225
<!-- tabs:end -->
200226

201227
### 方法二:动态规划

lcci/17.09.Get Kth Magic Number/README_EN.md

+26
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,32 @@ int getKthMagicNumber(int k) {
191191
}
192192
```
193193
194+
```swift
195+
class Solution {
196+
private let factors = [3, 5, 7]
197+
198+
func getKthMagicNumber(_ k: Int) -> Int {
199+
var heap: [Int] = [1]
200+
var seen = Set<Int>()
201+
seen.insert(1)
202+
203+
var value = 1
204+
for _ in 1...k {
205+
value = heap.removeFirst()
206+
for factor in factors {
207+
let nextValue = value * factor
208+
if !seen.contains(nextValue) {
209+
heap.append(nextValue)
210+
seen.insert(nextValue)
211+
}
212+
}
213+
heap.sort()
214+
}
215+
return value
216+
}
217+
}
218+
```
219+
194220
<!-- tabs:end -->
195221

196222
### Solution 2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
private let factors = [3, 5, 7]
3+
4+
func getKthMagicNumber(_ k: Int) -> Int {
5+
var heap: [Int] = [1]
6+
var seen = Set<Int>()
7+
seen.insert(1)
8+
9+
var value = 1
10+
for _ in 1...k {
11+
value = heap.removeFirst()
12+
for factor in factors {
13+
let nextValue = value * factor
14+
if !seen.contains(nextValue) {
15+
heap.append(nextValue)
16+
seen.insert(nextValue)
17+
}
18+
}
19+
heap.sort()
20+
}
21+
return value
22+
}
23+
}

0 commit comments

Comments
 (0)