简介
Go的标准包Container中包含了常用的容器类型,包括conatiner/list
,container/heap
,container/ring
。本篇主要介绍如何使用container/heap
包实现最小堆。关于堆的概念请参阅相关资料。
heap包
container/heap包仅仅提供了最小堆的操作,没有提供堆的数据结构,堆的数据结构必须我们自己实现。heap包提供了一个heap.Interface接口来作为堆的操作(heap包提供)和堆的数据结构(我们自己实现)之间的桥梁,堆的数据结构必须满足此接口:
container/heap−−−−−−−−−−−−−
type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}
sort.Interface定义在sort包中:
sort−−−−
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
也就是说,我们自己实现的堆的数据结构需要定义以上5个方法才能与heap包合作。注意这些方法都是由heap包来调用的,我们自己不能调用这些方法。
heap包提供了5个函数来对堆进行操作:
// 当索引为i的元素的值改变时,调用此函数重建堆
func Fix(h Interface, i int)
// 初始化堆,在调用其他堆操作函数前应调用此函数以完成初始化
func Init(h Interface)
// 弹出堆中的最小元素,返回弹出的元素
func Pop(h Interface) interface{}
// 添加元素到堆
func Push(h Interface, x interface{})
// 移除索引为i的元素,返回被移除的元素
func Remove(h Interface, i int) interface{}
示例
下面通过一个例子详细解释如何使用heap包。本例模拟一个单词列表,每使用一个单词就会在列表中记录该单词的使用次数,在列表过长时,将使用次数最少的单词删除。完整代码如下:
package main
import (
"container/heap"
"fmt"
)
// Word 表示单词列表中的一个单词
type Word struct {
text string // 单词
used int // 使用次数
index int // 索引
}
// 定义单词列表,通常使用数组实现堆的存储
type WordList []*Word
//
// 实现以下5个函数以满足 heap.Interface 接口
//
func (wl WordList) Len() int {
return len(wl)
}
func (wl WordList) Less(i, j int) bool {
// 根据单词使用计数判断元素大小:单词使用计数越小,则元素值越小
return wl[i].used < wl[j].used
}
func (wl WordList) Swap(i, j int) {
wl[i], wl[j] = wl[j], wl[i] // 交换元素
wl[i].index, wl[j].index = i, j // 交换索引
}
func (wl *WordList) Push(x interface{}) {
word := x.(*Word)
word.index = len(*wl) // 根据接口说明,新元素的索引为Len()
*wl = append(*wl, word)
}
func (wl *WordList) Pop() interface{} {
// 根据接口说明,Pop()应移除并返回索引为Len()-1的元素
word := (*wl)[len(*wl)-1]
word.index = -1
*wl = (*wl)[0 : len(*wl)-1]
return word
}
// 该函数用来统计单词使用数量
func (wl *WordList) used(word string) {
// 如果单词已在列表中,则增加使用计数
i := 0
for i = 0; i < len(*wl); i++ {
if (*wl)[i].text == word {
(*wl)[i].used++
heap.Fix(wl, (*wl)[i].index) // 由于改变了索引为index的元素的大小,
// 因此调用Fix重建堆
break
}
}
// 否则,添加单词到单词列表
if i == len(*wl) {
heap.Push(wl, &Word{
text: word,
used: 1, // 使用计数为1
index: -1,
})
}
}
// 限制单词列表长度,如果当前长度超过n,则将使用最少的单词移除,直到长度小于等于n为止
func (wl *WordList) limitTo(n int) {
for wl.Len() > n {
word := heap.Pop(wl).(*Word)
fmt.Printf("Removed \"%s\" which has been used %d times\n",
word.text, word.used)
}
}
// 调试用,打印表示堆的切片
func (wl *WordList) debugPrint() {
for i := 0; i < wl.Len(); i++ {
fmt.Printf("\"%s\" at index %d used %d times\n",
(*wl)[i].text, (*wl)[i].index, (*wl)[i].used)
}
}
func main() {
words := []string{
"Gopher", "Tomcat", "Gopher", "Cynhard",
"Gopher", "Tomcat", "Tomcat", "Gopher",
"Go", "Go", "Heap"}
wl := make(WordList, 0)
// 使用任何堆操作之前,必须先进行初始化
// 除非wl为空,或者已经排好序了
heap.Init(&wl)
for _, word := range words {
wl.used(word)
}
wl.debugPrint()
wl.limitTo(3)
wl.debugPrint()
wl.limitTo(0)
}
另外,官方也给出了两个示例:
第一个示例实现了一个简单的int堆:
// This example demonstrates an integer heap built using the heap interface.
package heap_test
import (
"container/heap"
"fmt"
)
// An IntHeap is a min-heap of ints.
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 and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*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
}
// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func Example_intHeap() {
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))
}
// Output:
// minimum: 1
// 1 2 3 5
}
第二个示例实现了一个优先队列,与我们的单词列表例子差不多:
// This example demonstrates a priority queue built using the heap interface.
package heap_test
import (
"container/heap"
"fmt"
)
// An Item is something we manage in a priority queue.
type Item struct {
value string // The value of the item; arbitrary.
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
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 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func Example_priorityQueue() {
// Some items and their priorities.
items := map[string]int{
"banana": 3, "apple": 2, "pear": 4,
}
// Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq := make(PriorityQueue, len(items))
i := 0
for value, priority := range items {
pq[i] = &Item{
value: value,
priority: priority,
index: i,
}
i++
}
heap.Init(&pq)
// Insert a new item and then modify its priority.
item := &Item{
value: "orange",
priority: 1,
}
heap.Push(&pq, item)
pq.update(item, item.value, 5)
// Take the items out; they arrive in decreasing priority order.
for pq.Len() > 0 {
item := heap.Pop(&pq).(*Item)
fmt.Printf("%.2d:%s ", item.priority, item.value)
}
// Output:
// 05:orange 04:pear 03:banana 02:apple
}
总结
- 使用container/heap包实现堆。
- container/heap包仅封装了堆的操作,没有封装堆的数据结构,需要自己实现堆的数据结构。
- 堆的数据结构必须满足heap.Interface接口。container/heap包调用该接口的实现以完成具体操作。