Skip to content

Commit 003b091

Browse files
committed
Solution Top K Frequent Elements
1 parent 30f5aae commit 003b091

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
3+
var tables: [Int: Int] = [:]
4+
5+
for num in nums {
6+
tables[num] = (tables[num] ?? 0) + 1
7+
}
8+
9+
let values = tables.values.sorted().reversed().prefix(k) // k개의 frequent
10+
let result = tables.compactMap { (key: Int, value: Int) -> Int? in
11+
if values.contains(value) {
12+
return key
13+
}
14+
return nil
15+
}
16+
return result
17+
}
18+
}

0 commit comments

Comments
 (0)