Skip to content

Commit fa9ea36

Browse files
committed
top-k frequent elements solution
1 parent d5c6168 commit fa9ea36

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package youngDaLee
2+
3+
import "sort"
4+
5+
func topKFrequent(nums []int, k int) []int {
6+
frequencyMap := make(map[int]int)
7+
for _, num := range nums {
8+
frequencyMap[num]++
9+
}
10+
11+
type freqPair struct {
12+
num int
13+
count int
14+
}
15+
16+
freqPairs := make([]freqPair, 0, len(frequencyMap))
17+
for num, count := range frequencyMap {
18+
freqPairs = append(freqPairs, freqPair{num, count})
19+
}
20+
21+
sort.Slice(freqPairs, func(i, j int) bool {
22+
return freqPairs[i].count > freqPairs[j].count
23+
})
24+
25+
result := make([]int, k)
26+
for i := 0; i < k; i++ {
27+
result[i] = freqPairs[i].num
28+
}
29+
30+
return result
31+
}

0 commit comments

Comments
 (0)