container/heap

最後更新


container/heap 提供堆積(heap)演算法:讓你隨時以 O(log n) 的成本取出「目前最小(或最優先)」的元素,常用來實作優先佇列。

這個套件做什麼


堆積像是「永遠把最急的工作放最上面」的待辦清單。和每次都重新排序整份清單不同,堆積只維持一個較寬鬆的規則:父節點不大於子節點。這樣新增與取出都只要 O(log n),而最小的元素永遠在索引 0。
典型用途:
  • 優先佇列(priority queue):工作排程、事件模擬,依優先度處理
  • 從大量資料中找前 K 大或前 K 小
  • 最短路徑演算法(Dijkstra)、合併多個已排序串列

container/heap 本身不存資料,它只提供演算法。你準備一個型別(通常是切片)並實作 heap.Interface,再用 heap.Init、heap.Push、heap.Pop 操作它。
和相近工具的差別:
工具適合
container/heap資料持續增減,每次只需要取出最小/最大的那個
slices.Sort一次性排序全部資料
slices.Min/slices.Max偶爾找一次最小/最大值

匯入


  1. import "container/heap"

常用 API


heap.Interface


要使用堆積,型別必須實作 heap.Interface:也就是 sort.Interface 的三個方法(Len、Less、Swap),加上 Push 與 Pop。
  • Less(i, j) 決定誰在上面:用 < 是最小堆積(min-heap),用 > 就是最大堆積
  • Push(x) 把 x 加到切片尾端
  • Pop() 移除並回傳切片的最後一個元素

Push 與 Pop 要用指標接收者,因為它們會改變切片長度(觀念見 指標接收者)。
注意:型別上的 Push/Pop 方法是給 heap 套件內部呼叫的。你自己操作時要呼叫套件函式 heap.Push(h, x)、heap.Pop(h),直接呼叫方法會破壞堆積的順序。
簽名:
  1. type Interface interface {
  2. sort.Interface
  3. Push(x any)
  4. Pop() any
  5. }

範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type IntHeap []int
  7. func (h IntHeap) Len() int { return len(h) }
  8. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  9. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  10. func (h *IntHeap) Push(x any) {
  11. *h = append(*h, x.(int))
  12. }
  13. func (h *IntHeap) Pop() any {
  14. old := *h
  15. n := len(old)
  16. x := old[n-1]
  17. *h = old[:n-1]
  18. return x
  19. }
  20. func main() {
  21. h := &IntHeap{5, 2, 8}
  22. heap.Init(h)
  23. fmt.Println("min:", (*h)[0])
  24. var _ heap.Interface = h
  25. fmt.Println("len:", h.Len())
  26. }

輸出:
  1. min: 2
  2. len: 3

Init


把一個任意順序的集合整理成合法的堆積,成本 O(n)。已經有一批資料時先呼叫 Init,之後再用 Push、Pop。空集合可以不呼叫。
簽名:
  1. func Init(h Interface)

範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type IntHeap []int
  7. func (h IntHeap) Len() int { return len(h) }
  8. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  9. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  10. func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
  11. func (h *IntHeap) Pop() any {
  12. old := *h
  13. x := old[len(old)-1]
  14. *h = old[:len(old)-1]
  15. return x
  16. }
  17. func main() {
  18. h := &IntHeap{9, 4, 7, 1, 8}
  19. fmt.Println("before:", *h)
  20. heap.Init(h)
  21. fmt.Println("after: ", *h)
  22. fmt.Println("min: ", (*h)[0])
  23. }

輸出:
  1. before: [9 4 7 1 8]
  2. after: [1 4 7 9 8]
  3. min: 1

Init 之後切片不是完全排序,只保證最小值在最前面、父節點不大於子節點。

Push 與 Pop


heap.Push 加入一個元素並維持堆積規則;heap.Pop 移除並回傳最小的元素。兩者都是 O(log n)。不斷 Pop 直到空,就會依序得到由小到大的結果。
Pop 回傳 any,取出後要用型別斷言轉回原本型別(見 型別斷言與型別 switch)。
注意:對空堆積呼叫 heap.Pop 會在你的 Pop 方法裡索引越界而 panic,呼叫前先檢查 Len() > 0。
簽名:
  1. func Push(h Interface, x any)
  2. func Pop(h Interface) any

範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type IntHeap []int
  7. func (h IntHeap) Len() int { return len(h) }
  8. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  9. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  10. func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
  11. func (h *IntHeap) Pop() any {
  12. old := *h
  13. x := old[len(old)-1]
  14. *h = old[:len(old)-1]
  15. return x
  16. }
  17. func main() {
  18. h := &IntHeap{}
  19. for _, n := range []int{5, 1, 9, 3} {
  20. heap.Push(h, n)
  21. }
  22. heap.Push(h, 0)
  23. for h.Len() > 0 {
  24. fmt.Print(heap.Pop(h).(int), " ")
  25. }
  26. fmt.Println()
  27. }

輸出:
  1. 0 1 3 5 9

優先佇列與 Fix


實務上堆積裡放的通常是結構體,例如「工作名稱 + 優先度」。如果某個元素的優先度在加入之後改變,呼叫 heap.Fix(h, i) 讓它移到正確位置,比先移除再加入更有效率。
要知道元素目前在哪個索引,常見做法是在結構體裡存一個 index 欄位,並在 Swap 與 Push 時更新它。下面的範例用最大堆積(Less 用 >),優先度高的先處理。
簽名:
  1. func Fix(h Interface, i int)

範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type Task struct {
  7. Name string
  8. Priority int
  9. index int
  10. }
  11. type TaskQueue []*Task
  12. func (q TaskQueue) Len() int { return len(q) }
  13. func (q TaskQueue) Less(i, j int) bool { return q[i].Priority > q[j].Priority }
  14. func (q TaskQueue) Swap(i, j int) {
  15. q[i], q[j] = q[j], q[i]
  16. q[i].index = i
  17. q[j].index = j
  18. }
  19. func (q *TaskQueue) Push(x any) {
  20. t := x.(*Task)
  21. t.index = len(*q)
  22. *q = append(*q, t)
  23. }
  24. func (q *TaskQueue) Pop() any {
  25. old := *q
  26. n := len(old)
  27. t := old[n-1]
  28. old[n-1] = nil
  29. t.index = -1
  30. *q = old[:n-1]
  31. return t
  32. }
  33. func main() {
  34. q := &TaskQueue{}
  35. backup := &Task{Name: "backup", Priority: 1}
  36. heap.Push(q, &Task{Name: "email", Priority: 3})
  37. heap.Push(q, backup)
  38. heap.Push(q, &Task{Name: "deploy", Priority: 5})
  39. backup.Priority = 10
  40. heap.Fix(q, backup.index)
  41. for q.Len() > 0 {
  42. t := heap.Pop(q).(*Task)
  43. fmt.Printf("%s (priority %d)\n", t.Name, t.Priority)
  44. }
  45. }

輸出:
  1. backup (priority 10)
  2. deploy (priority 5)
  3. email (priority 3)

Pop 中把 old[n-1] 設成 nil,是為了讓被取出的元素不再被底層陣列引用,可以被垃圾回收。

Remove


移除並回傳索引 i 的元素,成本 O(log n)。用在「取消某個尚未處理的工作」這類情境。
注意:i 必須是有效索引(0 <= i < Len()),否則會 panic。
簽名:
  1. func Remove(h Interface, i int) any

範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. "slices"
  6. )
  7. type IntHeap []int
  8. func (h IntHeap) Len() int { return len(h) }
  9. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  10. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  11. func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
  12. func (h *IntHeap) Pop() any {
  13. old := *h
  14. x := old[len(old)-1]
  15. *h = old[:len(old)-1]
  16. return x
  17. }
  18. func main() {
  19. h := &IntHeap{4, 8, 1, 6, 3}
  20. heap.Init(h)
  21. i := slices.Index(*h, 6)
  22. removed := heap.Remove(h, i)
  23. fmt.Println("removed:", removed)
  24. for h.Len() > 0 {
  25. fmt.Print(heap.Pop(h), " ")
  26. }
  27. fmt.Println()
  28. }

輸出:
  1. removed: 6
  2. 1 3 4 8

找出前 K 大


一個常見技巧:維持一個大小為 K 的最小堆積。每讀到一個新值就 Push,堆積超過 K 個時 Pop 掉最小的;全部讀完後,堆積裡剩下的就是最大的 K 個。記憶體只用 O(K),適合資料量很大或資料是串流進來的情況。
範例:
  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. "slices"
  6. )
  7. type IntHeap []int
  8. func (h IntHeap) Len() int { return len(h) }
  9. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  10. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  11. func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
  12. func (h *IntHeap) Pop() any {
  13. old := *h
  14. x := old[len(old)-1]
  15. *h = old[:len(old)-1]
  16. return x
  17. }
  18. func topK(nums []int, k int) []int {
  19. h := &IntHeap{}
  20. for _, n := range nums {
  21. heap.Push(h, n)
  22. if h.Len() > k {
  23. heap.Pop(h)
  24. }
  25. }
  26. result := slices.Clone(*h)
  27. slices.Sort(result)
  28. slices.Reverse(result)
  29. return result
  30. }
  31. func main() {
  32. scores := []int{55, 92, 13, 78, 92, 41, 88, 67}
  33. fmt.Println(topK(scores, 3))
  34. }

輸出:
  1. [92 92 88]

重點整理


  • container/heap 只提供演算法,資料結構由你實作 heap.Interface(sort.Interface + Push + Pop)
  • Less 用 < 是最小堆積、用 > 是最大堆積;索引 0 永遠是最優先的元素
  • 操作時呼叫套件函式 heap.Push/heap.Pop,不要直接呼叫型別上的方法
  • 元素優先度改變後用 heap.Fix;取消元素用 heap.Remove
  • 對空堆積 Pop 會 panic,先檢查 Len()

資料來源