广告
返回顶部
首页 > 资讯 > 后端开发 > GO >深入了解Golang官方container/heap用法
  • 578
分享到

深入了解Golang官方container/heap用法

2024-04-02 19:04:59 578人浏览 独家记忆
摘要

目录开篇container/heap核心函数InitPop/PushRemoveFix如何接入IntHeap优先队列按时间戳排序总结开篇 在 golang 的标准库 containe

开篇

golang 的标准库 container 中,包含了几种常见的数据结构的实现,其实是非常好的学习材料,我们可以从中回顾一下经典的数据结构,看看 Golang 的官方团队是如何思考的。

  • container/list 双向链表
  • container/ring 循环链表;
  • container/heap 堆。

今天我们就来看看 container/heap 的源码,了解一下官方的同学是怎么设计,我们作为开发者又该如何使用。

container/heap

包 heap 为所有实现了 heap.Interface 的类型提供堆操作。 一个堆即是一棵树, 这棵树的每个节点的值都比它的子节点的值要小, 而整棵树最小的值位于树根(root), 也即是索引 0 的位置上。

堆是实现优先队列的一种常见方法。 为了构建优先队列, 用户在实现堆接口时, 需要让 Less() 方法返回逆序的结果, 这样就可以在使用 Push 添加元素的同时, 通过 Pop 移除队列中优先级最高的元素了。

heap 是实现优先队列的常见方式。Golang 中的 heap 是最小堆,需要满足两个特点:

  • 堆中某个结点的值总是不小于其父结点的值;
  • 堆总是一棵完全二叉树

所以,根节点就是 heap 中最小的值。

有一个很有意思的现象,大家知道,Golang 此前是没有泛型的,作为一个强类型的语言,要实现通用的写法一般会采用【代码生成】或者【反射】。

而作为官方包,Golang 希望提供给大家一种简单的接入方式,官方提供好算法的内核,大家接入就 ok。采用的是定义一个接口,开发者来实现的方式。

在 container/heap 包中,我们一上来就能找到这个 Interface 定义:

// The Interface type describes the requirements
// for a type using the routines in this package.
// Any type that implements it may be used as a
// min-heap with the following invariants (established after
// Init has been called or if the data is empty or sorted):
//
//	!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
//
// Note that Push and Pop in this interface are for package heap's
// implementation to call. To add and remove things from the heap,
// use heap.Push and heap.Pop.
type Interface interface {
	sort.Interface
	Push(x any) // add x as element Len()
	Pop() any   // remove and return element Len() - 1.
}

除了 Push 和 Pop 两个堆自己的方法外,还内置了一个 sort.Interface:

type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}

核心函数

Init

作为开发者,我们基于自己的结构体,实现了 container/heap.Interface,该怎么用呢?

首先需要调用 heap.Init(h Interface) 方法,传入我们的实现:

// Init establishes the heap invariants required by the other routines in this package.
// Init is idempotent with respect to the heap invariants
// and may be called whenever the heap invariants may have been invalidated.
// The complexity is O(n) where n = h.Len().
func Init(h Interface) {
	// heapify
	n := h.Len()
	for i := n/2 - 1; i >= 0; i-- {
		down(h, i, n)
	}
}

在执行任何堆操作之前, 必须对堆进行初始化。 Init 操作对于堆不变性(invariants)具有幂等性, 无论堆不变性是否有效, 它都可以被调用。

Init 函数的复杂度为 O(n) , 其中 n 等于 h.Len() 。

Pop/Push

作为堆,当然需要实现【插入】和【弹出】这两个能力,这里 any 其实就是 interface{}

// Push pushes the element x onto the heap.
// The complexity is O(log n) where n = h.Len().
func Push(h Interface, x any) {
	h.Push(x)
	up(h, h.Len()-1)
}

// Pop removes and returns the minimum element (according to Less) from the heap.
// The complexity is O(log n) where n = h.Len().
// Pop is equivalent to Remove(h, 0).
func Pop(h Interface) any {
	n := h.Len() - 1
	h.Swap(0, n)
	down(h, 0, n)
	return h.Pop()
}
  • Push 函数将值为 x 的元素推入到堆里面,该函数的复杂度为 O(log(n)) 。
  • Pop 函数根据 Less 的结果, 从堆中移除并返回具有最小值的元素, 等同于执行 Remove(h, 0),复杂度为 O(log(n))。(n 等于 h.Len() )

Remove

// Remove removes and returns the element at index i from the heap.
// The complexity is O(log n) where n = h.Len().
func Remove(h Interface, i int) any {
	n := h.Len() - 1
	if n != i {
		h.Swap(i, n)
		if !down(h, i, n) {
			up(h, i)
		}
	}
	return h.Pop()
}

Remove 函数移除堆中索引为 i 的元素,复杂度为 O(log(n))

Fix

有时候我们改变了堆上的元素,需要重新排序。这时候就可以用 Fix 来完成。

这里需要注意:

  • 【先修改索引 i 上的元素的值然后再执行 Fix】
  • 【先调用 Remove(h, i) 然后再使用 Push 操作将新值重新添加到堆里面】

二者具有同等的效果。但 Fix 的成本会小一些。复杂度为 O(log(n))。

// Fix re-establishes the heap ordering after the element at index i has changed its value.
// Changing the value of the element at index i and then calling Fix is equivalent to,
// but less expensive than, calling Remove(h, i) followed by a Push of the new value.
// The complexity is O(log n) where n = h.Len().
func Fix(h Interface, i int) {
	if !down(h, i, h.Len()) {
		up(h, i)
	}
}

如何接入

将自定义结构实现上面的 heap.Interface 接口后,先进行 Init,随后调用上面我们提到的 Push / Pop / Remove / Fix 即可。其实大多数情况下用前两个就足够了,我们直接看两个例子。

IntHeap

先来看一个简单例子,基于整型 integer 实现一个最小堆。

  • 首先定义一个自己的类型,在这个例子中是 int,所以这一步跳过;
  • 定义一个 Heap 类型,这里我们使用 type IntHeap []int
  • 实现自定义 Heap 类型的 5 个方法,三个 sort 的,加上 Push 和 Pop。

有了实现,我们 Init 后就可以 Push 进去元素了,这里我们初始化 2,1,5,又 push 了个 3,最后打印结果完美按照从小到大输出。

// This example demonstrates an integer heap built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An IntHeap is a min-heap of ints.
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 any) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func main() {
	h := &IntHeap{2, 1, 5}
	heap.Init(h)
	heap.Push(h, 3)
	fmt.Printf("minimum: %d\n", (*h)[0])
	for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
}

Output:
minimum: 1
1 2 3 5

优先队列

官方也给出了实现优先队列的方法,我们需要一个 priority 作为权值,加上 value。

  • Value 表示元素值
  • Priority 用于排序
  • Index 元素在对上的索引值,用于更新元素的操作。
// This example demonstrates a priority queue built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An Item is something we manage in a priority queue.
type Item struct {
	value    string // The value of the item; arbitrary.
	priority int    // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x any) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() any {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func main() {
	// Some items and their priorities.
	items := map[string]int{
		"banana": 3, "apple": 2, "pear": 4,
	}

	// Create a priority queue, put the items in it, and
	// establish the priority queue (heap) invariants.
	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,
		}
		i++
	}
	heap.Init(&pq)

	// Insert a new item and then modify its priority.
	item := &Item{
		value:    "orange",
		priority: 1,
	}
	heap.Push(&pq, item)
	pq.update(item, item.value, 5)

	// Take the items out; they arrive in decreasing priority order.
	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
}


Output
05:orange 04:pear 03:banana 02:apple

按时间戳排序

package util

import (
	"container/heap"
)

type TimeSortedQueueItem struct {
	Time  int64
	Value interface{}
}

type TimeSortedQueue []*TimeSortedQueueItem

func (q TimeSortedQueue) Len() int           { return len(q) }
func (q TimeSortedQueue) Less(i, j int) bool { return q[i].Time < q[j].Time }
func (q TimeSortedQueue) Swap(i, j int)      { q[i], q[j] = q[j], q[i] }

func (q *TimeSortedQueue) Push(v interface{}) {
	*q = append(*q, v.(*TimeSortedQueueItem))
}

func (q *TimeSortedQueue) Pop() interface{} {
	n := len(*q)
	item := (*q)[n-1]
	*q = (*q)[0 : n-1]
	return item
}

func NewTimeSortedQueue(items ...*TimeSortedQueueItem) *TimeSortedQueue {
	q := make(TimeSortedQueue, len(items))
	for i, item := range items {
		q[i] = item
	}
	heap.Init(&q)
	return &q
}

func (q *TimeSortedQueue) PushItem(time int64, value interface{}) {
	heap.Push(q, &TimeSortedQueueItem{
		Time:  time,
		Value: value,
	})
}

func (q *TimeSortedQueue) PopItem() interface{} {
	if q.Len() == 0 {
		return nil
	}

	return heap.Pop(q).(*TimeSortedQueueItem).Value
}

这里我们封装了一个 TimeSortedQueue,里面包含一个时间戳,以及我们实际的值。实现之后,就可以暴露对外的 NewTimeSortedQueue 方法用来初始化,这里调用 heap.Init。

同时做一层简单的封装就可以对外使用了。

总结

Go语言中heap的实现采用了一种 “模板设计模式”,用户实现自定义堆时,只需要实现heap.Interface接口中的函数,然后应用heap.Push、heap.Pop等方法就能够实现想要的功能,堆管理方法是由Go实现好的,存放在heap中。

到此这篇关于深入了解Golang官方container/heap用法的文章就介绍到这了,更多相关Golang container/heap用法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: 深入了解Golang官方container/heap用法

本文链接: https://www.lsjlt.com/news/121211.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 深入了解Golang官方container/heap用法
    目录开篇container/heap核心函数InitPop/PushRemoveFix如何接入IntHeap优先队列按时间戳排序总结开篇 在 Golang 的标准库 containe...
    99+
    2022-11-11
  • 深入了解Golang中的run方法
    Go是一种快速,可靠和开源的编程语言。Go语言通过其高效的并发性和垃圾回收器以及C的速度,用于构建高效和可扩展的网络服务器和系统编程。让我们深入了解Golang中的run方法。run()方法是golang中重要的一种方法,可以用于创建新的协...
    99+
    2023-05-14
  • 深入了解golang中的静态方法
    Golang是一门支持面向对象编程的编程语言,但是它的面向对象编程方式有些不同于传统的面向对象编程语言。有一点不同是Golang中没有类(class)的概念,也没有Java中的静态方法(static method)。但是Golang中提供了...
    99+
    2023-05-14
  • 深入了解Golang包的获取方法
    目录1.获取远程包2.应用1.获取远程包 go 语言有一个获取远程包的工具就是 go get,目前 go get 支持多数开源社区 (例如:github、googlecode、bit...
    99+
    2022-11-13
  • 深入了解Golang的指针用法
    目录1.指针类型的变量2.Go只有值传递,没有引用传递3.for range与指针4.闭包与指针5.指针与内存逃逸与C语言一样,Go语言中同样有指针,通过指针,我们可以只传递变量的内...
    99+
    2022-11-13
  • 深入了解SparkSQL的运用及方法
    目录一:SparkSQL1.SparkSQL简介2.SparkSQL运行原理3.SparkSQL特点二、SparkSQL运用一:SparkSQL 1.SparkSQL简介 Spark...
    99+
    2022-11-13
  • 深入了解git rebase的使用方法
    Git是目前最流行的版本控制工具之一,它带来了一些改变,包括支持多个分支,并且有助于管理代码版本更新。当我们在团队中合作开发时,往往会遇到一些时候需要合并分支,而这时Git Rebase的使用就显得极为重要。下面我们来一起了解一下Git R...
    99+
    2023-10-22
  • 深入了解Golang中Slice切片的使用
    目录写在前面上代码分析原因总结写在前面 周日下午在家学习,看到一个关于切片的问题,在网上找了一些资料,做个总结。 上代码 func main() { sl := make([]in...
    99+
    2023-02-27
    Golang Slice切片使用 Golang Slice切片 Golang Slice
  • 深入了解Golang中占位符的使用
    目录基本常见常用的占位符较少使用的占位符进制和浮点使用占位符指针占位符基本常见常用的占位符 %s%d%v , %v+ , %+v%T , %q 写一个 demo 来看看上面占位符的效...
    99+
    2023-03-11
    Golang占位符使用 Golang占位符 Go 占位符
  • 深入了解Golang中reflect反射的使用
    目录1. 介绍2. 方法示例2.1 通过反射获取对象的键(类型)和值2.2 反射对象的类型和属性3. 反射对Json的操作3.1 反射与Json属性解析3.2 Json包的序列化与反...
    99+
    2023-05-20
    Golang reflect反射 Go reflect反射 Golang reflect
  • 深入聊聊 Golang 的使用方法
    在互联网行业的大环境下,Golang(简称Go)已成为一个备受瞩目的编程语言,众多互联网公司如:谷歌、阿里巴巴、腾讯等,都已将其作为主力开发语言。Go 语言在因特网时代不断壮大的背景下,以并发编程,运行速度以及简单易用的特点,受到了众多程序...
    99+
    2023-05-14
  • 深入了解git checkout命令的使用方法
    Git是一种流行的版本控制系统,它允许开发人员跟踪和控制代码的更改。Git有许多命令供使用,其中之一就是git checkout。git checkout命令可以用于切换分支、还原更改以及更改工作目录中文件的状态等。在这篇文章中,我们将深入...
    99+
    2023-10-22
  • 深入了解Golang 哈希算法之MD5、SHA-1和SHA-256
    目录1. 哈希算法基础1.1 哈希算法的定义1.2 哈希算法的应用2. Golang 中的哈希算法2.1 哈希算法接口2.2 常用的哈希函数2.2.1 MD52.2.2 SHA-12...
    99+
    2023-05-20
    Golang 哈希算法 Golang 哈希算法MD5 Golang 哈希算法SHA-1 Golang 哈希算法SHA-256
  • 深入了解Golang网络编程Net包的使用
    目录1.TCP 服务2.TCP 连接在系统调用层面的实现3.Go中TCP连接的实现4.结语​最近做了一个项目,其中用到了网络编程,下面和大家分享下在Go中网络编程的实现。在Go中, ...
    99+
    2022-11-13
  • 深入了解Java中Synchronized的各种使用方法
    目录Synchronized关键字Synchronized修饰实例方法Synchronized修饰静态方法Sychronized修饰多个方法Synchronized修饰实例方法代码块...
    99+
    2022-11-13
    Java Synchronized用法 Java Synchronized Java Synchronized使用
  • 深入了解Java方法的重载与重写
    目录1.方法的重载1.1.基本介绍1.2.重载的好处1.3.重载使用细节1.4.可变参数2.方法的重写2.1.基本介绍2.2.重写的好处2.3.重写的细节3.重写与重写的对比1.方法...
    99+
    2022-11-13
  • 深入了解C++优先队列(priority_queue)的使用方法
    目录优先队列的基本概念优先队列的使用方法优先队列元素的排序规则元素的自定义排序优先队列的时间复杂度总结优先队列的基本概念 在计算机科学中,优先队列是一种抽象数据类型,它与队列相似,但...
    99+
    2023-05-18
    C++优先队列 C++队列
  • 深入了解Java内部类的用法
    目录1.内部类分类和概念2.局部内部类3.匿名内部类(重要)基于接口的匿名内部类基于类的匿名内部类一些细节匿名内部类的最佳实践4.成员内部类5.静态内部类1.内部类分类和概念 jav...
    99+
    2022-11-13
  • Flask深入了解Jinja2引擎的用法
    目录Jinja2Jinja2语句扩展Jinja2模板继承Jinja2 想象一下这样一个场景,如果对于某个网站来说,如果你充值了Vip,你才可以看到隐藏内容了。你该怎么做呢? 这个适合...
    99+
    2022-11-11
  • 深入了解Python中Lambda函数的用法
    目录什么是Lambda函数过滤列表中的元素和map()函数的联用和apply()方法的联用不太适合使用的场景今天来给大家推荐一个Python当中超级好用的内置函数,那便是lambda...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作