func(h *NodeHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x }
funcmergeKLists(lists []*ListNode) *ListNode { h := &NodeHeap{} heap.Init(h) // 将所有链表的头节点加入堆 for _, list := range lists { if list != nil { heap.Push(h, list) } } dummy := &ListNode{} current := dummy for h.Len() > 0 { node := heap.Pop(h).(*ListNode) current.Next = node current = current.Next if node.Next != nil { heap.Push(h, node.Next) } } return dummy.Next }
2. 数组中的第K个最大元素 (LeetCode 215)
1 2 3 4 5 6 7 8 9 10 11 12 13
funcfindKthLargest(nums []int, k int)int { h := &MinHeap{} heap.Init(h) for _, num := range nums { heap.Push(h, num) if h.Len() > k { heap.Pop(h) } } return heap.Pop(h).(int) }
functopKFrequent(nums []int, k int) []int { // 统计频率 frequency := make(map[int]int) for _, num := range nums { frequency[num]++ } // 创建优先队列 pq := &PriorityQueue{} heap.Init(pq) // 将元素加入队列 for value, count := range frequency { heap.Push(pq, &Item{value: value, count: count}) if pq.Len() > k { heap.Pop(pq) } } // 收集结果 result := make([]int, k) for i := k - 1; i >= 0; i-- { result[i] = heap.Pop(pq).(*Item).value } return result }