如何在Golang中使用container/heap实现堆

答案是使用container/heap包需实现heap.interface接口,通过定义lenless、Swap、Push、Pop方法构建最小或最大堆,如IntHeap实现最小堆,TaskHeap按Priority字段排序。

如何在Golang中使用container/heap实现堆

golang中,container/heap 是一个包,提供了堆(优先队列)的接口和操作方法。它本身不直接提供堆的实现,而是要求你定义一个满足 heap.Interface 接口的类型。通过实现这个接口,你可以构建最小堆或最大堆。

1. 实现 heap.Interface 接口

要使用 container/heap,你需要定义一个类型(通常是切片),并实现以下五个方法:

  • Len() int:返回元素个数
  • Less(i, j int) bool:定义堆的排序规则(如最小堆返回 a[i] < a[j])
  • Swap(i, j int):交换两个元素
  • Push(x interface{}):向堆中添加元素
  • Pop() interface{}:从堆中移除并返回根元素

2. 构建一个最小堆示例

下面是一个整数最小堆的完整实现:

 package main  import (     "container/heap"     "fmt" )  // 定义一个类型,底层用切片表示 type IntHeap []int  // 实现 Len 方法 func (h IntHeap) Len() int           { return len(h) }  // 实现 Less 方法:最小堆,小的在前面 func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }  // 实现 Swap 方法 func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }  // Push 方法:注意接收者是指针 func (h *IntHeap) Push(x interface{}) {     *h = append(*h, x.(int)) }  // Pop 方法:移除并返回堆顶 func (h *IntHeap) Pop() interface{} {     old := *h     n := len(old)     x := old[n-1]     *h = old[0 : n-1]     return x }  func main() {     h := &IntHeap{}     heap.Init(h)      // 插入元素     heap.Push(h, 3)     heap.Push(h, 1)     heap.Push(h, 4)     heap.Push(h, 2)      // 弹出元素(从小到大)     for h.Len() > 0 {         fmt.Print(heap.Pop(h), " ") // 输出: 1 2 3 4     } } 

3. 构建最大堆

只需修改 Less 方法的逻辑:

立即学习go语言免费学习笔记(深入)”;

 func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] } // 大的优先 

这样就变成了最大堆,每次 Pop 返回当前最大值。

如何在Golang中使用container/heap实现堆

如知AI笔记

如知笔记——支持markdown的在线笔记,支持ai智能写作、AI搜索,支持DeepseekR1满血大模型

如何在Golang中使用container/heap实现堆27

查看详情 如何在Golang中使用container/heap实现堆

4. 使用结构体构建更复杂的堆

实际开发中,常需要根据结构体字段排序。例如按任务优先级排序:

 type Task struct {     ID   int     Priority int }  type TaskHeap []*Task  func (h TaskHeap) Len() int            { return len(h) } func (h TaskHeap) Less(i, j int) bool  { return h[i].Priority < h[j].Priority } // 优先级小的先执行 func (h TaskHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }  func (h *TaskHeap) Push(x interface{}) { *h = append(*h, x.(*Task)) } func (h *TaskHeap) Pop() interface{}   {      old := *h     n := len(old)     x := old[n-1]     *h = old[0 : n-1]     return x } 

然后像上面一样初始化和使用即可。

基本上就这些。只要实现好接口,就能利用 container/heap 提供的 Init、Push、Pop、Remove、Fix 等方法高效操作堆。注意 Push 和 Pop 必须用指针接收者,而 Len、Less、Swap 用值接收者更高效。

上一篇
下一篇
text=ZqhQzanResources