347. Top K high-frequency elements
Article directory
Question description
Problem solving ideas
Sort the array in reverse order according to frequency, and then return the top k data
Solution code
func topKFrequent(nums []int, k int) []int {
m := make(map[int]int, 0)
for i := len(nums) - 1; i >= 0; i-- {
m[nums[i]]++
}
res := make([]int, 0, len(m))
for k, _ := range m {
res = append(res, k)
}
// 降序
sort.Slice(res, func(a, b int) bool {
return m[res[a]] > m[res[b]]
})
return res[:k]
}