heap包提供了对任意类型(实现了heap.Interface接口)的堆操作。

heap是常用的实现优先队列的方法。要创建一个优先队列,实现一个具有使用(负的)优先级作为比较的依据的Less方法的Heap接口,如此一来可用Push添加项目而用Pop取出队列最高优先级的项目。

Func

  1. // 一个堆在使用任何堆操作之前应先初始化
  2. // Init函数对于堆的约束性是幂等的(多次执行无意义)
  3. func Init(h Interface)
  4. // 向堆h中插入元素x,并保持堆的约束性。复杂度O(log(n)),其中n等于h.Len()。
  5. func Push(h Interface, x interface{})
  6. // 删除并返回堆h中的最小元素。复杂度O(log(n)),其中n等于h.Len()。等价于Remove(h, 0)。
  7. func Pop(h Interface) interface{}
  8. // 删除堆中的第i个元素,并保持堆的约束性。复杂度O(log(n)),其中n等于h.Len()。
  9. func Remove(h Interface, i int) interface{}
  10. // 在修改第i个元素后,调用本函数修复堆,比删除第i个元素后插入新元素更有效率。
  11. // 复杂度O(log(n)),其中n等于h.Len()。
  12. func Fix(h Interface, i int)

type Interface

注意接口的Push和Pop方法是供heap包调用的,请使用heap.Push和heap.Pop来向一个堆添加或者删除元素。

  1. type Interface interface {
  2. sort.Interface
  3. Push(x interface{}) // 向末尾添加元素
  4. Pop() interface{} // 从末尾删除元素
  5. }

Demo

IntHeap

  1. // This example demonstrates an integer heap built using the heap interface.
  2. package heap_test
  3. import (
  4. "container/heap"
  5. "fmt"
  6. )
  7. // An IntHeap is a min-heap of ints.
  8. type IntHeap []int
  9. func (h IntHeap) Len() int { return len(h) }
  10. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  11. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  12. func (h *IntHeap) Push(x interface{}) {
  13. // Push and Pop use pointer receivers because they modify the slice's length,
  14. // not just its contents.
  15. *h = append(*h, x.(int))
  16. }
  17. func (h *IntHeap) Pop() interface{} {
  18. old := *h
  19. n := len(old)
  20. x := old[n-1]
  21. *h = old[0 : n-1]
  22. return x
  23. }
  24. // This example inserts several ints into an IntHeap, checks the minimum,
  25. // and removes them in order of priority.
  26. func Example_intHeap() {
  27. h := &IntHeap{2, 1, 5}
  28. heap.Init(h)
  29. heap.Push(h, 3)
  30. fmt.Printf("minimum: %d\n", (*h)[0])
  31. for h.Len() > 0 {
  32. fmt.Printf("%d ", heap.Pop(h))
  33. }
  34. // Output:
  35. // minimum: 1
  36. // 1 2 3 5
  37. }

PriorityQueue

  1. package heap_test
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. // An Item is something we manage in a priority queue.
  7. type Item struct {
  8. value string // The value of the item; arbitrary.
  9. priority int // The priority of the item in the queue.
  10. // The index is needed by update and is maintained by the heap.Interface methods.
  11. index int // The index of the item in the heap.
  12. }
  13. // A PriorityQueue implements heap.Interface and holds Items.
  14. type PriorityQueue []*Item
  15. func (pq PriorityQueue) Len() int { return len(pq) }
  16. func (pq PriorityQueue) Less(i, j int) bool {
  17. // 从低到高排序,即pop 返回优先级最高的
  18. return pq[i].priority > pq[j].priority
  19. }
  20. func (pq PriorityQueue) Swap(i, j int) {
  21. pq[i], pq[j] = pq[j], pq[i]
  22. pq[i].index = i
  23. pq[j].index = j
  24. }
  25. func (pq *PriorityQueue) Push(x interface{}) {
  26. n := len(*pq)
  27. item := x.(*Item)
  28. item.index = n
  29. *pq = append(*pq, item)
  30. }
  31. func (pq *PriorityQueue) Pop() interface{} {
  32. old := *pq
  33. n := len(old)
  34. item := old[n-1]
  35. item.index = -1 // for safety
  36. *pq = old[0 : n-1]
  37. return item
  38. }
  39. // update modifies the priority and value of an Item in the queue.
  40. func (pq *PriorityQueue) update(item *Item, value string, priority int) {
  41. item.value = value
  42. item.priority = priority
  43. heap.Fix(pq, item.index)
  44. }
  45. // This example creates a PriorityQueue with some items, adds and manipulates an item,
  46. // and then removes the items in priority order.
  47. func Example_priorityQueue() {
  48. // Some items and their priorities.
  49. items := map[string]int{
  50. "banana": 3, "apple": 2, "pear": 4,
  51. }
  52. // Create a priority queue, put the items in it, and
  53. // establish the priority queue (heap) invariants.
  54. pq := make(PriorityQueue, len(items))
  55. i := 0
  56. for value, priority := range items {
  57. pq[i] = &Item{
  58. value: value,
  59. priority: priority,
  60. index: i,
  61. }
  62. i++
  63. }
  64. heap.Init(&pq)
  65. // Insert a new item and then modify its priority.
  66. item := &Item{
  67. value: "orange",
  68. priority: 1,
  69. }
  70. heap.Push(&pq, item)
  71. pq.update(item, item.value, 5)
  72. // Take the items out; they arrive in decreasing priority order.
  73. for pq.Len() > 0 {
  74. item := heap.Pop(&pq).(*Item)
  75. fmt.Printf("%.2d:%s ", item.priority, item.value)
  76. }
  77. // Output:
  78. // 05:orange 04:pear 03:banana 02:apple
  79. }