老师,leetcode的这道问题,我觉得使用最大堆也是可以解决的。
将Map中记录的元素->频率键值对全部放入堆中,然后从堆中推出k个元素,不就是频率最高的k个元素么
下面是我用go实现的代码(go的heap需要自己实现下接口,代码有点多…),leetcode提交也是OK的
func topKFrequent(nums []int, k int) []int {
// 统计每个元素出现的频率
freq := make(map[int]int)
for _, v := range nums {
freq[v]++
}
minHeap := &FeqMinHeap{}
// 将记录元素->频率的所有数据对放入堆中
for k, v := range freq {
*minHeap = append(*minHeap, Feq{
val: k,
count: v,
})
}
// heapify构建堆
heap.Init(minHeap)
res := make([]int, k)
// 从堆中取出k个元素即为频率最高的k个元素
for i := 0; i < k && minHeap.Len() > 0; i++ {
res[i] = heap.Pop(minHeap).(Feq).val
}
return res
}
type Feq struct {
val int
count int
}
type FeqMinHeap []Feq
func (pq FeqMinHeap) Len() int {
return len(pq)
}
func (pq FeqMinHeap) Less(i, j int) bool {
return pq[i].count > pq[j].count
}
func (pq FeqMinHeap) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *FeqMinHeap) Push(x interface{}) {
*pq = append(*pq, x.(Feq))
}
func (pq *FeqMinHeap) Pop() interface{} {
n := len(*pq) - 1
res := (*pq)[n]
*pq = (*pq)[:n]
return res
}