File tree 3 files changed +75
-0
lines changed
lcci/17.09.Get Kth Magic Number
3 files changed +75
-0
lines changed Original file line number Diff line number Diff line change @@ -196,6 +196,32 @@ int getKthMagicNumber(int k) {
196
196
}
197
197
```
198
198
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
+
199
225
<!-- tabs:end -->
200
226
201
227
### 方法二:动态规划
Original file line number Diff line number Diff line change @@ -191,6 +191,32 @@ int getKthMagicNumber(int k) {
191
191
}
192
192
```
193
193
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
+
194
220
<!-- tabs:end -->
195
221
196
222
### Solution 2
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments