Top K Frequent Elements Solutions in Go
Number 347
Difficulty Medium
Acceptance 61.3%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport "container/heap"func topKFrequent(nums []int, k int) []int {m := make(map[int]int)for _, n := range nums {m[n]++}q := PriorityQueue{}for key, count := range m {heap.Push(&q, &Item{key: key, count: count})}var result []intfor len(result) < k {item := heap.Pop(&q).(*Item)result = append(result, item.key)}return result}// Item definetype Item struct {key intcount int}// A PriorityQueue implements heap.Interface and holds Items.type PriorityQueue []*Itemfunc (pq PriorityQueue) Len() int {return len(pq)}func (pq PriorityQueue) Less(i, j int) bool {// 注意:因为golang中的heap是按最小堆组织的,所以count越大,Less()越小,越靠近堆顶.return pq[i].count > pq[j].count}func (pq PriorityQueue) Swap(i, j int) {pq[i], pq[j] = pq[j], pq[i]}// Push definefunc (pq *PriorityQueue) Push(x interface{}) {item := x.(*Item)*pq = append(*pq, item)}// Pop definefunc (pq *PriorityQueue) Pop() interface{} {n := len(*pq)item := (*pq)[n-1]*pq = (*pq)[:n-1]return item}