小頂堆,實作golang的堆介面:
type bigHeap []int
func (h bigHeap) Len() int {
return len(h)
}
func (h bigHeap) Less(i,j int) bool {
return h[i] < h[j]
}
func (h bigHeap) Swap(i,j int) {
h[i],h[j] = h[j],h[i]
}
func (h *bigHeap) Push(x interface{}) {
*h = append(*h,x.(int))
}
func (h *bigHeap) Pop() interface{} {
n := len(*h)
x := *h[n-1]
*h = *h[:n-1]
return x
}
如果我要實作大頂堆,那么就要把上面這五個函式重復一遍嗎,但其實只需要修改一個Less函式就行了,重復一遍有些多余。并且,實作堆介面也就實作了sort排序介面,排序介面里面通過sort.Reverse(sort.Interface)函式,可以得到一個逆轉Less函式的新介面,是否可以在小頂堆的基礎上,通過逆轉Less函式得到大頂堆呢?我試過好多次,但寫出來不太對,有沒有大佬指點一下,謝謝
uj5u.com熱心網友回復:
噢噢,問題寫錯,這個代碼是小頂堆轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266818.html
標籤:go語言
