File tree Expand file tree Collapse file tree 2 files changed +77
-0
lines changed
lcof2/剑指 Offer II 060. 出现频率最高的 k 个数字 Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Original file line number Diff line number Diff line change @@ -198,6 +198,47 @@ impl Solution {
198
198
}
199
199
```
200
200
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
+
201
242
<!-- tabs: end -->
202
243
203
244
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments