重点介绍
container
package main
import (
"container/heap"
"fmt"
)
type Interface interface {
sort.Interface
Push(x interface{})
Pop() interface{}
}
sort
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
- 故要用标准库的heap,需要实现下列五个接口函数,如下
{
Len() int
Less(i, j int) bool
Swap(i, j int)
Push(x interface{})
Pop() interface{}
}
{
h := &IntHeap{} //创建IntHeap类型的原始数据
func Init(h Interface) //对heap进行初始化,生成小根堆(或大根堆)
func Push(h Interface, x interface{}) //往堆插入内容
func Pop(h Interface) interface{} //从堆顶中取出元素
func Remove(h Interface, i int) interface{} //从指定位置删除数据,并返回删除的数据
func Fix(h Interface, i int) //从i位置发生改变后,对堆再平衡,优先级队列使用到了该方法
}
实践
package main
import (
"fmt"
"container/heap"
)
func main() {
h := &IntHeap{2, 1, 5, 6, 4, 3, 7, 9, 8, 0} //创建slice
heap.Init(h) //初始化heap
fmt.Println(*h)
//[0 1 3 6 2 5 7 9 8 4]
fmt.Println(heap.Pop(h))
//0
heap.Push(h, 6)
fmt.Println(*h)
//[1 2 3 6 4 5 7 9 8 6]
for len(*h) > 0 {
fmt.Printf("%d ", heap.Pop(h))
}
//1 2 3 4 5 6 6 7 8 9
}
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{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n - 1] //注意这里,虽然取得是索引n - 1位置的元素,实际上对应的是h[0],即堆顶元素
*h = old[0 : n - 1]
return x
}