深入了解Golang官方container/heap用法
開篇
在 Golang 的標準庫 container 中,包含了幾種常見的數(shù)據(jù)結構的實現(xiàn),其實是非常好的學習材料,我們可以從中回顧一下經典的數(shù)據(jù)結構,看看 Golang 的官方團隊是如何思考的。
- container/list 雙向鏈表;
- container/ring 循環(huán)鏈表;
- container/heap 堆。
今天我們就來看看 container/heap 的源碼,了解一下官方的同學是怎么設計,我們作為開發(fā)者又該如何使用。
container/heap
包 heap 為所有實現(xiàn)了 heap.Interface 的類型提供堆操作。 一個堆即是一棵樹, 這棵樹的每個節(jié)點的值都比它的子節(jié)點的值要小, 而整棵樹最小的值位于樹根(root), 也即是索引 0 的位置上。
堆是實現(xiàn)優(yōu)先隊列的一種常見方法。 為了構建優(yōu)先隊列, 用戶在實現(xiàn)堆接口時, 需要讓 Less() 方法返回逆序的結果, 這樣就可以在使用 Push 添加元素的同時, 通過 Pop 移除隊列中優(yōu)先級最高的元素了。
heap 是實現(xiàn)優(yōu)先隊列的常見方式。Golang 中的 heap 是最小堆,需要滿足兩個特點:
- 堆中某個結點的值總是不小于其父結點的值;
- 堆總是一棵完全二叉樹。
所以,根節(jié)點就是 heap 中最小的值。
有一個很有意思的現(xiàn)象,大家知道,Golang 此前是沒有泛型的,作為一個強類型的語言,要實現(xiàn)通用的寫法一般會采用【代碼生成】或者【反射】。
而作為官方包,Golang 希望提供給大家一種簡單的接入方式,官方提供好算法的內核,大家接入就 ok。采用的是定義一個接口,開發(fā)者來實現(xiàn)的方式。
在 container/heap 包中,我們一上來就能找到這個 Interface 定義:
// The Interface type describes the requirements
// for a type using the routines in this package.
// Any type that implements it may be used as a
// min-heap with the following invariants (established after
// Init has been called or if the data is empty or sorted):
//
// !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
//
// Note that Push and Pop in this interface are for package heap's
// implementation to call. To add and remove things from the heap,
// use heap.Push and heap.Pop.
type Interface interface {
sort.Interface
Push(x any) // add x as element Len()
Pop() any // remove and return element Len() - 1.
}
除了 Push 和 Pop 兩個堆自己的方法外,還內置了一個 sort.Interface:
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
核心函數(shù)
Init
作為開發(fā)者,我們基于自己的結構體,實現(xiàn)了 container/heap.Interface,該怎么用呢?
首先需要調用 heap.Init(h Interface) 方法,傳入我們的實現(xiàn):
// Init establishes the heap invariants required by the other routines in this package.
// Init is idempotent with respect to the heap invariants
// and may be called whenever the heap invariants may have been invalidated.
// The complexity is O(n) where n = h.Len().
func Init(h Interface) {
// heapify
n := h.Len()
for i := n/2 - 1; i >= 0; i-- {
down(h, i, n)
}
}
在執(zhí)行任何堆操作之前, 必須對堆進行初始化。 Init 操作對于堆不變性(invariants)具有冪等性, 無論堆不變性是否有效, 它都可以被調用。
Init 函數(shù)的復雜度為 O(n) , 其中 n 等于 h.Len() 。
Pop/Push
作為堆,當然需要實現(xiàn)【插入】和【彈出】這兩個能力,這里 any 其實就是 interface{}
// Push pushes the element x onto the heap.
// The complexity is O(log n) where n = h.Len().
func Push(h Interface, x any) {
h.Push(x)
up(h, h.Len()-1)
}
// Pop removes and returns the minimum element (according to Less) from the heap.
// The complexity is O(log n) where n = h.Len().
// Pop is equivalent to Remove(h, 0).
func Pop(h Interface) any {
n := h.Len() - 1
h.Swap(0, n)
down(h, 0, n)
return h.Pop()
}
- Push 函數(shù)將值為 x 的元素推入到堆里面,該函數(shù)的復雜度為 O(log(n)) 。
- Pop 函數(shù)根據(jù) Less 的結果, 從堆中移除并返回具有最小值的元素, 等同于執(zhí)行 Remove(h, 0),復雜度為 O(log(n))。(n 等于 h.Len() )
Remove
// Remove removes and returns the element at index i from the heap.
// The complexity is O(log n) where n = h.Len().
func Remove(h Interface, i int) any {
n := h.Len() - 1
if n != i {
h.Swap(i, n)
if !down(h, i, n) {
up(h, i)
}
}
return h.Pop()
}
Remove 函數(shù)移除堆中索引為 i 的元素,復雜度為 O(log(n))
Fix
有時候我們改變了堆上的元素,需要重新排序。這時候就可以用 Fix 來完成。
這里需要注意:
- 【先修改索引 i 上的元素的值然后再執(zhí)行 Fix】
- 【先調用 Remove(h, i) 然后再使用 Push 操作將新值重新添加到堆里面】
二者具有同等的效果。但 Fix 的成本會小一些。復雜度為 O(log(n))。
// Fix re-establishes the heap ordering after the element at index i has changed its value.
// Changing the value of the element at index i and then calling Fix is equivalent to,
// but less expensive than, calling Remove(h, i) followed by a Push of the new value.
// The complexity is O(log n) where n = h.Len().
func Fix(h Interface, i int) {
if !down(h, i, h.Len()) {
up(h, i)
}
}
如何接入
將自定義結構實現(xiàn)上面的 heap.Interface 接口后,先進行 Init,隨后調用上面我們提到的 Push / Pop / Remove / Fix 即可。其實大多數(shù)情況下用前兩個就足夠了,我們直接看兩個例子。
IntHeap
先來看一個簡單例子,基于整型 integer 實現(xiàn)一個最小堆。
- 首先定義一個自己的類型,在這個例子中是 int,所以這一步跳過;
- 定義一個 Heap 類型,這里我們使用
type IntHeap []int; - 實現(xiàn)自定義 Heap 類型的 5 個方法,三個 sort 的,加上 Push 和 Pop。
有了實現(xiàn),我們 Init 后就可以 Push 進去元素了,這里我們初始化 2,1,5,又 push 了個 3,最后打印結果完美按照從小到大輸出。
// This example demonstrates an integer heap built using the heap interface.
package main
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 any) {
// 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() any {
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 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))
}
}
Output:
minimum: 1
1 2 3 5
優(yōu)先隊列
官方也給出了實現(xiàn)優(yōu)先隊列的方法,我們需要一個 priority 作為權值,加上 value。
- Value 表示元素值
- Priority 用于排序
- Index 元素在對上的索引值,用于更新元素的操作。
// This example demonstrates a priority queue built using the heap interface.
package main
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 any) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() any {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
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 main() {
// 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
按時間戳排序
package util
import (
"container/heap"
)
type TimeSortedQueueItem struct {
Time int64
Value interface{}
}
type TimeSortedQueue []*TimeSortedQueueItem
func (q TimeSortedQueue) Len() int { return len(q) }
func (q TimeSortedQueue) Less(i, j int) bool { return q[i].Time < q[j].Time }
func (q TimeSortedQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *TimeSortedQueue) Push(v interface{}) {
*q = append(*q, v.(*TimeSortedQueueItem))
}
func (q *TimeSortedQueue) Pop() interface{} {
n := len(*q)
item := (*q)[n-1]
*q = (*q)[0 : n-1]
return item
}
func NewTimeSortedQueue(items ...*TimeSortedQueueItem) *TimeSortedQueue {
q := make(TimeSortedQueue, len(items))
for i, item := range items {
q[i] = item
}
heap.Init(&q)
return &q
}
func (q *TimeSortedQueue) PushItem(time int64, value interface{}) {
heap.Push(q, &TimeSortedQueueItem{
Time: time,
Value: value,
})
}
func (q *TimeSortedQueue) PopItem() interface{} {
if q.Len() == 0 {
return nil
}
return heap.Pop(q).(*TimeSortedQueueItem).Value
}
這里我們封裝了一個 TimeSortedQueue,里面包含一個時間戳,以及我們實際的值。實現(xiàn)之后,就可以暴露對外的 NewTimeSortedQueue 方法用來初始化,這里調用 heap.Init。
同時做一層簡單的封裝就可以對外使用了。
總結
Go語言中heap的實現(xiàn)采用了一種 “模板設計模式”,用戶實現(xiàn)自定義堆時,只需要實現(xiàn)heap.Interface接口中的函數(shù),然后應用heap.Push、heap.Pop等方法就能夠實現(xiàn)想要的功能,堆管理方法是由Go實現(xiàn)好的,存放在heap中。
到此這篇關于深入了解Golang官方container/heap用法的文章就介紹到這了,更多相關Golang container/heap用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
go-zero讀取請求體出現(xiàn)EOF錯誤的解決方法
這篇文章主要為大家詳細介紹了go-zero讀取請求體出現(xiàn)EOF錯誤時如何解決,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2025-02-02
GoLang之使用Context控制請求超時的實現(xiàn)
這篇文章主要介紹了GoLang之使用Context控制請求超時的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04
golang復制文件夾移動到另一個文件夾實現(xiàn)方法詳解
這篇文章主要為大家介紹了golang復制文件夾并移動到另一個文件夾實現(xiàn)方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07

