網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
開(kāi)篇
在 Golang 的標(biāo)準(zhǔn)庫(kù) container 中,包含了幾種常見(jiàn)的數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn),其實(shí)是非常好的學(xué)習(xí)材料,我們可以從中回顧一下經(jīng)典的數(shù)據(jù)結(jié)構(gòu),看看 Golang 的官方團(tuán)隊(duì)是如何思考的。
- container/list 雙向鏈表;
- container/ring 循環(huán)鏈表;
- container/heap 堆。
今天我們就來(lái)看看 container/heap 的源碼,了解一下官方的同學(xué)是怎么設(shè)計(jì),我們作為開(kāi)發(fā)者又該如何使用。
container/heap
包 heap 為所有實(shí)現(xiàn)了 heap.Interface 的類型提供堆操作。 一個(gè)堆即是一棵樹(shù), 這棵樹(shù)的每個(gè)節(jié)點(diǎn)的值都比它的子節(jié)點(diǎn)的值要小, 而整棵樹(shù)最小的值位于樹(shù)根(root), 也即是索引 0 的位置上。
堆是實(shí)現(xiàn)優(yōu)先隊(duì)列的一種常見(jiàn)方法。 為了構(gòu)建優(yōu)先隊(duì)列, 用戶在實(shí)現(xiàn)堆接口時(shí), 需要讓 Less() 方法返回逆序的結(jié)果, 這樣就可以在使用 Push 添加元素的同時(shí), 通過(guò) Pop 移除隊(duì)列中優(yōu)先級(jí)最高的元素了。
heap 是實(shí)現(xiàn)優(yōu)先隊(duì)列的常見(jiàn)方式。Golang 中的 heap 是最小堆,需要滿足兩個(gè)特點(diǎn):
- 堆中某個(gè)結(jié)點(diǎn)的值總是不小于其父結(jié)點(diǎn)的值;
- 堆總是一棵完全二叉樹(shù)。
所以,根節(jié)點(diǎn)就是 heap 中最小的值。
有一個(gè)很有意思的現(xiàn)象,大家知道,Golang 此前是沒(méi)有泛型的,作為一個(gè)強(qiáng)類型的語(yǔ)言,要實(shí)現(xiàn)通用的寫(xiě)法一般會(huì)采用【代碼生成】或者【反射】。
而作為官方包,Golang 希望提供給大家一種簡(jiǎn)單的接入方式,官方提供好算法的內(nèi)核,大家接入就 ok。采用的是定義一個(gè)接口,開(kāi)發(fā)者來(lái)實(shí)現(xiàn)的方式。
在 container/heap 包中,我們一上來(lái)就能找到這個(gè) 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 兩個(gè)堆自己的方法外,還內(nèi)置了一個(gè) sort.Interface:
type Interface interface { Len() int Less(i, j int) bool Swap(i, j int) }
核心函數(shù)
Init
作為開(kāi)發(fā)者,我們基于自己的結(jié)構(gòu)體,實(shí)現(xiàn)了 container/heap.Interface,該怎么用呢?
首先需要調(diào)用 heap.Init(h Interface)
方法,傳入我們的實(shí)現(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í)行任何堆操作之前, 必須對(duì)堆進(jìn)行初始化。 Init 操作對(duì)于堆不變性(invariants)具有冪等性, 無(wú)論堆不變性是否有效, 它都可以被調(diào)用。
Init 函數(shù)的復(fù)雜度為 O(n) , 其中 n 等于 h.Len() 。
Pop/Push
作為堆,當(dāng)然需要實(shí)現(xiàn)【插入】和【彈出】這兩個(gè)能力,這里 any 其實(shí)就是 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ù)的復(fù)雜度為 O(log(n)) 。
- Pop 函數(shù)根據(jù) Less 的結(jié)果, 從堆中移除并返回具有最小值的元素, 等同于執(zhí)行 Remove(h, 0),復(fù)雜度為 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 的元素,復(fù)雜度為 O(log(n))
Fix
有時(shí)候我們改變了堆上的元素,需要重新排序。這時(shí)候就可以用 Fix 來(lái)完成。
這里需要注意:
- 【先修改索引 i 上的元素的值然后再執(zhí)行 Fix】
- 【先調(diào)用 Remove(h, i) 然后再使用 Push 操作將新值重新添加到堆里面】
二者具有同等的效果。但 Fix 的成本會(huì)小一些。復(fù)雜度為 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) } }
如何接入
將自定義結(jié)構(gòu)實(shí)現(xiàn)上面的 heap.Interface 接口后,先進(jìn)行 Init,隨后調(diào)用上面我們提到的 Push / Pop / Remove / Fix 即可。其實(shí)大多數(shù)情況下用前兩個(gè)就足夠了,我們直接看兩個(gè)例子。
IntHeap
先來(lái)看一個(gè)簡(jiǎn)單例子,基于整型 integer 實(shí)現(xiàn)一個(gè)最小堆。
- 首先定義一個(gè)自己的類型,在這個(gè)例子中是 int,所以這一步跳過(guò);
- 定義一個(gè) Heap 類型,這里我們使用
type IntHeap []int
; - 實(shí)現(xiàn)自定義 Heap 類型的 5 個(gè)方法,三個(gè) sort 的,加上 Push 和 Pop。
有了實(shí)現(xiàn),我們 Init 后就可以 Push 進(jìn)去元素了,這里我們初始化 2,1,5,又 push 了個(gè) 3,最后打印結(jié)果完美按照從小到大輸出。
// 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)先隊(duì)列
官方也給出了實(shí)現(xiàn)優(yōu)先隊(duì)列的方法,我們需要一個(gè) priority 作為權(quán)值,加上 value。
- Value 表示元素值
- Priority 用于排序
- Index 元素在對(duì)上的索引值,用于更新元素的操作。
// 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
按時(shí)間戳排序
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 }
這里我們封裝了一個(gè) TimeSortedQueue,里面包含一個(gè)時(shí)間戳,以及我們實(shí)際的值。實(shí)現(xiàn)之后,就可以暴露對(duì)外的 NewTimeSortedQueue 方法用來(lái)初始化,這里調(diào)用 heap.Init。
同時(shí)做一層簡(jiǎn)單的封裝就可以對(duì)外使用了。
總結(jié)
Go語(yǔ)言中heap的實(shí)現(xiàn)采用了一種 “模板設(shè)計(jì)模式”,用戶實(shí)現(xiàn)自定義堆時(shí),只需要實(shí)現(xiàn)heap.Interface接口中的函數(shù),然后應(yīng)用heap.Push、heap.Pop等方法就能夠?qū)崿F(xiàn)想要的功能,堆管理方法是由Go實(shí)現(xiàn)好的,存放在heap中。
原文鏈接:https://juejin.cn/post/7152136155410989092
相關(guān)推薦
- 2023-07-28 Cannot read properties of undefined (reading ‘push
- 2022-08-05 雪花算法工具類
- 2023-11-18 python字符串string的截取;獲取字符串內(nèi)的一串
- 2022-10-07 react性能優(yōu)化useMemo與useCallback使用對(duì)比詳解_React
- 2022-08-19 WPF在VisualTree上增加Visual_C#教程
- 2022-07-02 教你使用Pycharm配置遠(yuǎn)程Jupyter_python
- 2022-08-26 C++類模板實(shí)戰(zhàn)之vector容器的實(shí)現(xiàn)_C 語(yǔ)言
- 2023-06-03 python中with的具體用法_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支