Skip to content

Commit 4ca5f17

Browse files
klever34yanglbme
andauthored
feat: add swift implementation to lcof2 problem: No.060 (doocs#3103)
* feat: add swift implementation to lcof2 problem: No.060 * style: format code and docs with prettier --------- Co-authored-by: Libin YANG <[email protected]>
1 parent e293766 commit 4ca5f17

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

lcof2/剑指 Offer II 060. 出现频率最高的 k 个数字/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,47 @@ impl Solution {
198198
}
199199
```
200200

201+
#### Swift
202+
203+
```swift
204+
import HeapModule
205+
206+
class Solution {
207+
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
208+
var frequency: [Int: Int] = [:]
209+
for num in nums {
210+
frequency[num, default: 0] += 1
211+
}
212+
213+
var freqHeap = Heap<FreqElement>()
214+
for (key, value) in frequency {
215+
freqHeap.insert(.init(val: key, freq: value))
216+
if freqHeap.count > k {
217+
freqHeap.removeMin()
218+
}
219+
}
220+
var ans = [Int]()
221+
while let element = freqHeap.popMax() {
222+
ans.append(element.val)
223+
}
224+
return ans
225+
}
226+
}
227+
228+
struct FreqElement: Comparable {
229+
let val: Int
230+
let freq: Int
231+
232+
static func < (lhs: FreqElement, rhs: FreqElement) -> Bool {
233+
lhs.freq < rhs.freq
234+
}
235+
236+
static func == (lhs: FreqElement, rhs: FreqElement) -> Bool {
237+
lhs.freq == rhs.freq
238+
}
239+
}
240+
```
241+
201242
<!-- tabs:end -->
202243

203244
<!-- solution:end -->
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import HeapModule
2+
3+
class Solution {
4+
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
5+
var frequency: [Int: Int] = [:]
6+
for num in nums {
7+
frequency[num, default: 0] += 1
8+
}
9+
10+
var freqHeap = Heap<FreqElement>()
11+
for (key, value) in frequency {
12+
freqHeap.insert(.init(val: key, freq: value))
13+
if freqHeap.count > k {
14+
freqHeap.removeMin()
15+
}
16+
}
17+
var ans = [Int]()
18+
while let element = freqHeap.popMax() {
19+
ans.append(element.val)
20+
}
21+
return ans
22+
}
23+
}
24+
25+
struct FreqElement: Comparable {
26+
let val: Int
27+
let freq: Int
28+
29+
static func < (lhs: FreqElement, rhs: FreqElement) -> Bool {
30+
lhs.freq < rhs.freq
31+
}
32+
33+
static func == (lhs: FreqElement, rhs: FreqElement) -> Bool {
34+
lhs.freq == rhs.freq
35+
}
36+
}

0 commit comments

Comments
 (0)