예배 규칙서 찾다
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
문자

  • import "container/heap"

  • 概述

  • 索引

  • 例子

概述

Heap 包为任何实现 heap.Interface 的类型提供堆操作。堆是具有属性的树,每个节点是其子树中的最小值节点。

树中的最小元素是索引为0的根。

堆是实现优先级队列的常用方式。要构建一个优先级队列,请将具有(负)优先级的 Heap 接口作为 Less 方法的排序来执行,因此推送会添加项目,而Pop 将从队列中移除最高优先级的项目。这些例子包括这样的实现;文件example_pq_test.go 具有完整的源代码。

示例 (IntHeap)

本示例将几个 int 插入到 IntHeap 中,检查最小值,并按优先级顺序删除它们。

// 本示例演示了使用堆接口构建的整数堆。package mainimport ("container/heap""fmt")// IntHeap是一个整数的整数。type IntHeap []intfunc (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{}) {// Push和Pop使用指针接收器,因为它们修改切片的长度,// 不仅仅是其内容。*h = append(*h, x.(int))}func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]*h = old[0 : n-1]return x}// 本示例将几个int插入到IntHeap中,检查最小值,// 并按优先顺序删除它们。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))}}

示例 (PriorityQueue)

本示例使用某些项目创建 PriorityQueue,添加并操作项目,然后按优先级顺序删除项目。

// 此示例演示使用堆接口构建的优先级队列。package mainimport ("container/heap""fmt")// item是我们在优先队列中管理的item。type Item struct {
	value    string // item的值;任意取值。
	priority int    // 队列中项目的优先级。// 该索引是更新所需的,由heap.Interface方法维护。
	index int // 堆中项目的索引。}// PriorityQueue实现堆。接口并保存项目。type PriorityQueue []*Itemfunc (pq PriorityQueue) Len() int { return len(pq) }func (pq PriorityQueue) Less(i, j int) bool {// 我们希望Pop给我们最高的优先权,而不是最低的优先权,所以我们使用的比这里更大。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 interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n*pq = append(*pq, item)}func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety*pq = old[0 : n-1]return item}// 更新修改队列中某个项目的优先级和值。func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)}// 本示例使用某些项目创建PriorityQueue,添加和操作项目,// 然后按优先顺序删除这些项目。func main() {// 一些项目和它们的优先级。
	items := map[string]int{"banana": 3, "apple": 2, "pear": 4,}// 创建一个优先级队列,将其中的项目,和// 建立优先队列(堆)不变量。
	pq := make(PriorityQueue, len(items))
	i := 0for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,}
		i++}
	heap.Init(&pq)// 插入一个新项目,然后修改其优先级。
	item := &Item{
		value:    "orange",
		priority: 1,}
	heap.Push(&pq, item)
	pq.update(item, item.value, 5)// 取出项目;以优先顺序递减排列。for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)}}

索引

  • func Fix(h Interface, i int)

  • func Init(h Interface)

  • func Pop(h Interface) interface{}

  • func Push(h Interface, x interface{})

  • func Remove(h Interface, i int) interface{}

  • type Interface

示例

Package (IntHeap) Package (PriorityQueue)

包文件

heap.go

func Fix

func Fix(h Interface, i int)

Fix 在索引 i 处的元素已更改其值后重新建立堆排序。更改索引为 i 的元素的值,然后调用 Fix 相当于调用 Remove(h, i),然后再调用新值的代价。复杂度为 O(log(n)),其中 n = h.Len()。

func Init

func Init(h Interface)

必须在使用任何堆操作之前初始化堆。Init 对于堆不变式是幂等的,当堆不变量可能已经失效时可以调用Init。它的复杂性是 O(n),其中n = h.Len()。

func Pop

func Pop(h Interface) interface{}

Pop 从堆中删除最小元素(根据Less)并返回。复杂度为 O(log(n)),其中 n = h.Len()。它相当于 Remove(h, 0)。

func Push

func Push(h Interface, x interface{})

推动元素 x 到堆上。复杂度为 O(log(n)),其中 n = h.Len()。

func Remove

func Remove(h Interface, i int) interface{}

从堆中删除索引 i 处的元素。复杂度为 O(log(n)),其中 n = h.Len()。

type Interface

任何实现堆的类型 .Interface 可用作具有以下不变式的最小堆(在调用 Init 之后或数据为空或排序后建立):

!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()

请注意,此接口中的 Push 和 Pop 用于调用包堆的实现。要从堆中添加和删除东西,请使用 heap.Push 和 heap.Pop。

type Interface interface {
        sort.Interface        Push(x interface{}) // 将x添加为元素Len()        Pop() interface{}   // 删除并返回元素Len()-1.}
이전 기사: 다음 기사: