container/heap
本文是 Go 標准庫中 container/heap 包文檔的翻譯, 原文地址為: https://golang.org/pkg/container/heap/
概述
包 heap 為所有實現了 heap.Interface 的類型提供堆操作。 一個堆即是一棵樹, 這棵樹的每個節點的值都比它的子節點的值要小, 而整棵樹最小的值位於樹根(root), 也即是索引 0 的位置上。
堆是實現優先隊列的一種常見方法。 為了構建優先隊列, 用戶在實現堆接口時, 需要讓 Less() 方法返回逆序的結果, 這樣就可以在使用 Push 添加元素的同時, 通過 Pop 移除隊列中優先級最高的元素了。 具體的實現請看接下來展示的優先隊列例子。
示例:整數堆
// 這段代碼演示了如何使用堆接口構建一個整數堆。
package main import ( "container/heap" "fmt" ) // IntHeap 是一個由整數組成的最小堆。 type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x interface{}) { // Push 和 Pop 使用 pointer receiver 作為參數, // 因為它們不僅會對切片的內容進行調整,還會修改切片的長度。 *h = append(*h, x.(int)) } func (h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // 這個示例會將一些整數插入到堆里面, 接着檢查堆中的最小值, // 之后按順序從堆里面移除各個整數。 func main() { h := &IntHeap{2, 1, 5} heap.Init(h) heap.Push(h, 3) fmt.Printf("minimum: %d\n", (*h)[0]) for h.Len() > 0 { fmt.Printf("%d ", heap.Pop(h)) } }
執行結果:
minimum: 1 1 2 3 5
示例:優先隊列
// 這段代碼演示了如何使用堆接口構建一個優先隊列。
package main import ( "container/heap" "fmt" ) // Item 是優先隊列中包含的元素。 type Item struct { value string // 元素的值,可以是任意字符串。 priority int // 元素在隊列中的優先級。 // 元素的索引可以用於更新操作,它由 heap.Interface 定義的方法維護。 index int // 元素在堆中的索引。 } // 一個實現了 heap.Interface 接口的優先隊列,隊列中包含任意多個 Item 結構。 type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { // 我們希望 Pop 返回的是最大值而不是最小值, // 因此這里使用大於號進行對比。 return pq[i].priority > pq[j].priority } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(*pq) item := x.(*Item) item.index = n *pq = append(*pq, item) } func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] item.index = -1 // 為了安全性考慮而做的設置 *pq = old[0 : n-1] return item } // 更新函數會修改隊列中指定元素的優先級以及值。 func (pq *PriorityQueue) update(item *Item, value string, priority int) { item.value = value item.priority = priority heap.Fix