func(h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x }
// 347. 前 K 个高频元素 // https://leetcode-cn.com/problems/top-k-frequent-elements/ functopKFrequent(nums []int, k int) []int { m := make(map[int]int) ans := make([]int, k) h := &IntHeap{} heap.Init(h) for _, v := range nums { m[v]++ } for key, value := range m { heap.Push(h, [2]int{key, value}) if h.Len() > k { heap.Pop(h) } } for k > 0 { k-- ans[k] = heap.Pop(h).([2]int)[0] } return ans }