docs(heap): add go codes

This commit is contained in:
reanon
2023-01-13 10:25:25 +08:00
parent 8117a1d47d
commit 264a2ab6bc
3 changed files with 171 additions and 35 deletions
+17 -18
View File
@@ -4,10 +4,25 @@
package chapter_heap
// intHeap 是一个由整数组成的
// 通过实现 heap.Interface 来构建堆
// Go 语言中可以通过实现 heap.Interface 来构建整数大顶
// 实现 heap.Interface 需要同时实现 sort.Interface
type intHeap []any
// Push heap.Interface 的方法,实现推入元素到堆
func (h *intHeap) Push(x any) {
// Push 和 Pop 使用 pointer receiver 作为参数
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
*h = append(*h, x.(int))
}
// Pop heap.Interface 的方法,实现弹出堆顶元素
func (h *intHeap) Pop() any {
// 待出堆元素存放在最后
last := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return last
}
// Len sort.Interface 的方法
func (h *intHeap) Len() int {
return len(*h)
@@ -24,23 +39,7 @@ func (h *intHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
// Push heap.Interface 的方法
func (h *intHeap) Push(x any) {
// Push 和 Pop 使用 pointer receiver 作为参数
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
*h = append(*h, x.(int))
}
// Top 获取堆顶元素
func (h *intHeap) Top() any {
return (*h)[0]
}
// Pop heap.Interface 的方法,实现弹出堆顶元素
func (h *intHeap) Pop() any {
// 待出堆元素存放在最后
last := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return last
}