Skip to content

Commit 829d8a9

Browse files
authored
Merge pull request neetcode-gh#645 from sharansalian/leetcode/kotlin/347
Add 347-Top-k-Frequent-Elements.kt
2 parents 80165bf + e7dc301 commit 829d8a9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package kotlin
2+
3+
4+
fun main() {
5+
val nums = intArrayOf(1, 1, 1, 1, 2, 2, 3)
6+
}
7+
8+
fun topKFrequent(nums: IntArray, k: Int): IntArray {
9+
val res = mutableListOf<Int>()
10+
11+
val count = hashMapOf<Int, Int>()
12+
13+
val freq = MutableList<MutableList<Int>>(nums.size + 1) {
14+
mutableListOf()
15+
}
16+
17+
for (n in nums) {
18+
count[n] = count.getOrDefault(n, 0) + 1
19+
}
20+
21+
for ((n, c) in count) {
22+
freq[c].add(n)
23+
}
24+
25+
for (i in freq.size - 1 downTo 0) {
26+
for (n in freq[i]) {
27+
res.add(n)
28+
if (res.size == k) {
29+
return res.toIntArray()
30+
}
31+
}
32+
}
33+
34+
return intArrayOf()
35+
}

0 commit comments

Comments
 (0)