version: 1.10

package heap

import "container/heap"

概述

heap 包为任何实现了 heap.Interface 的类型提供对 heap 的操作。heap 是一种叫做最小树的数据结构,特点是每个结点都是子树的最小值。

树里的最小元素位于根结点,索引是0。

heap 是实现优先队列的常见方法。要建立一个优先队列,需要实现 Heap 接口,并在 Less 方法中以(负的)优先级作为排序的条件。下面的例子包含一个对应的实现,example_pq_test.go 文件包含完整的源码。

例子:

  1. // 这个例子演示了一个使用 heap 接口构建的整数堆。
  2. package heap_test
  3. import (
  4. "container/heap"
  5. "fmt"
  6. )
  7. // IntHeap 是元素为整数的最小堆。
  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 方法使用指针作为接收者是因为它们修改切片的长度,
  14. // 而不只是内容。
  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. // 这个例子插入若干整数到 IntHeap ,检查堆的最小值,
  25. // 然后按照优先级顺序删除它们。
  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. }

例子:

  1. // 这个例子演示了一个使用 heap 接口构建的优先队列。
  2. package heap_test
  3. import (
  4. "container/heap"
  5. "fmt"
  6. )
  7. // Item 是优先队列里的元素。
  8. type Item struct {
  9. value string // 元素的值,任何内容都行。
  10. priority int // 本元素在队列里的优先级。
  11. // index 被 update 方法使用,并被 heap.Interface 的方法维护。
  12. index int // 元素在堆里的索引。
  13. }
  14. // PriorityQueue 类型实现了 heap.Interface 并存储数据。
  15. type PriorityQueue []*Item
  16. func (pq PriorityQueue) Len() int { return len(pq) }
  17. func (pq PriorityQueue) Less(i, j int) bool {
  18. // 我们想要 Pop 函数获得最高的,而不是最低的,优先级所以我们这里使用大于号。
  19. return pq[i].priority > pq[j].priority
  20. }
  21. func (pq PriorityQueue) Swap(i, j int) {
  22. pq[i], pq[j] = pq[j], pq[i]
  23. pq[i].index = i
  24. pq[j].index = j
  25. }
  26. func (pq *PriorityQueue) Push(x interface{}) {
  27. n := len(*pq)
  28. item := x.(*Item)
  29. item.index = n
  30. *pq = append(*pq, item)
  31. }
  32. func (pq *PriorityQueue) Pop() interface{} {
  33. old := *pq
  34. n := len(old)
  35. item := old[n-1]
  36. item.index = -1 // for safety
  37. *pq = old[0 : n-1]
  38. return item
  39. }
  40. // update 方法修改队列里元素的优先级和值。
  41. func (pq *PriorityQueue) update(item *Item, value string, priority int) {
  42. item.value = value
  43. item.priority = priority
  44. heap.Fix(pq, item.index)
  45. }
  46. // 这个例子创建一个有若干元素的 PriorityQueue ,添加并操作一个元素,
  47. // 然后按照优先级顺序移除所有元素。
  48. func Example_priorityQueue() {
  49. // 若干带有优先级的元素。
  50. items := map[string]int{
  51. "banana": 3, "apple": 2, "pear": 4,
  52. }
  53. // 创建一个优先队列,把 items 放进去,然后建立优先队列(堆)的不变量。
  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. // 插入一个新的元素,然后修改它的优先级。
  66. item := &Item{
  67. value: "orange",
  68. priority: 1,
  69. }
  70. heap.Push(&pq, item)
  71. pq.update(item, item.value, 5)
  72. // 取出所有元素,它们应该按照优先级递减的顺序出来。
  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. }

索引

例子

文件

heap.go

func Fix

  1. func Fix(h Interface, i int)

Fix 函数在索引 i 的元素的值变化后重新构建堆。改变索引 i 处元素的值并调用 Fix 函数等价于调用 Remove(h, i) 然后调用 Push 函数来插入新的数据,不过代价较小。算法的时间复杂度是 O(log(n)),这里 n 等于 h.Len()。

func Init

  1. func Init(h Interface)

堆必须初始化后才能使用。Init 函数会初始化堆的不变量,并应该在堆的不变量无效时调用。算法的时间复杂度是 O(n),这里 n 等于 h.Len()。

func Pop

  1. func Pop(h Interface) interface{}

Pop 函数从堆里移除值最小的元素(通过 Less 方法)并返回该元素。算法的时间复杂度是 O(log(n)),这里 n 等于 h.Len()。它等价于 Remove(h, 0)。

func Push

  1. func Push(h Interface, x interface{})

Push 函数添加元素 x 到堆里。算法的时间复杂度是 O(log(n)),这里 n 等于 h.Len()。

func Remove

  1. func Remove(h Interface, i int) interface{}

Remove 函数从堆里移除索引 i 处的元素。算法的时间复杂度是 O(log(n)),这里 n 等于 h.Len()。

type Interface

  1. type Interface interface {
  2. sort.Interface
  3. Push(x interface{}) // add x as element Len()
  4. Pop() interface{} // remove and return element Len() - 1.
  5. }

任何实现了 heap.Interface 并且拥有如下不变量(在 Init 函数被调用后或数据是空或被排序后)的类型可以用作最小堆:

  1. !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()

注意:这个接口里的 Push 和 Pop 方法是heap包内部实现调用。如果要向堆里添加或移除数据,请使用 heap.Push 和 heap.Pop 函数。