mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-03 05:37:13 +00:00
docs(heap): add go codes
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user