Skip to content

Commit 51cd76c

Browse files
committed
top k frequent elements solution
1 parent 84d8fe6 commit 51cd76c

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
3+
var occurences = [Int: Int]()
4+
5+
for num in nums {
6+
if let occurence = occurences[num] {
7+
occurences[num] = occurence + 1
8+
} else {
9+
occurences[num] = 1
10+
}
11+
}
12+
13+
let numbers = occurences.keys.sorted { occurences[$0] ?? 0 > occurences[$1] ?? 0 }
14+
15+
return Array(numbers[0..<k])
16+
}
17+
}

0 commit comments

Comments
 (0)