【Golang】 堆heap的使用

重点介绍

  • 在标准库 container中,含有三种数据类型,分别是heap,list,ring;
  • Go语言提供heap容器,但是不提供相关操作,故需要我们进行相关函数的重写;

  • 导包
package main

import (
	"container/heap"
	"fmt"
)
  • heap中只实现了一个接口
type Interface interface {
	sort.Interface
	Push(x interface{})
	Pop() interface{}
}
  • 这个唯一接口中,还继承了 sort的接口,如下
type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}
  • 故要用标准库的heap,需要实现下列五个接口函数,如下
{
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
	Push(x interface{})
	Pop() interface{}
}
  • 在heap中,提供了一些方法,如下
{
	h := &IntHeap{}  //创建IntHeap类型的原始数据
	func Init(h Interface)  //对heap进行初始化,生成小根堆(或大根堆)
	func Push(h Interface, x interface{})  //往堆插入内容
	func Pop(h Interface) interface{}  //从堆顶中取出元素
	func Remove(h Interface, i int) interface{}  //从指定位置删除数据,并返回删除的数据
	func Fix(h Interface, i int)  //从i位置发生改变后,对堆再平衡,优先级队列使用到了该方法
}


实践

package main

import (
	"fmt"
	"container/heap"
)
func main() {
	h := &IntHeap{2, 1, 5, 6, 4, 3, 7, 9, 8, 0}  //创建slice
	heap.Init(h)  //初始化heap

	fmt.Println(*h)
	//[0 1 3 6 2 5 7 9 8 4]
	fmt.Println(heap.Pop(h))
	//0
	
	heap.Push(h, 6)

	fmt.Println(*h)
	//[1 2 3 6 4 5 7 9 8 6]
	for len(*h) > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
	//1 2 3 4 5 6 6 7 8 9
}


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 interface{}) {
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n - 1]  //注意这里,虽然取得是索引n - 1位置的元素,实际上对应的是h[0],即堆顶元素
	*h = old[0 : n - 1]
	return x
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值