什么是优先队列
普通队列和优先队列的比较
- 普通队列:先进先出,后进后出
- 优先队列:出对顺序和入队顺序无关,和优先级相关,优先级高的先出队
优先队列的应用
- 排队,VIP客户优先
- windows任务管理器,系统任务优先
优先队列不同实现方式的时间复杂度
堆
二叉堆是一颗完全二叉树。
go标准库中提供了堆的实现,直接参考:https://books.studygolang.com/The-Golang-Standard-Library-by-Example/chapter03/03.3.html
package heap
import "sort"
type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}
func Init(h Interface) {
// heapify
n := h.Len()
for i := n/2 - 1; i >= 0; i-- {
down(h, i, n)
}
}
func Push(h Interface, x interface{}) {
h.Push(x)
up(h, h.Len()-1)
}
func Pop(h Interface) interface{} {
n := h.Len() - 1
h.Swap(0, n)
down(h, 0, n)
return h.Pop()
}
func Remove(h Interface, i int) interface{} {
n := h.Len() - 1
if n != i {
h.Swap(i, n)
if !down(h, i, n) {
up(h, i)
}
}
return h.Pop()
}
func Fix(h Interface, i int) {
if !down(h, i, h.Len()) {
up(h, i)
}
}
func up(h Interface, j int) {
for {
i := (j - 1) / 2 // parent
if i == j || !h.Less(j, i) {
break
}
h.Swap(i, j)
j = i
}
}
func down(h Interface, i0, n int) bool {
i := i0
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && h.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
if !h.Less(j, i) {
break
}
h.Swap(i, j)
i = j
}
return i > i0
}
其中特别注意两个函数,一个是Remove
,一个是Fix
, Remove
的作用是移除堆中指定位置的元素,然后对数据结构进行调整,使其仍然构成一个堆,移除的方法是将该位置的元素用堆的最后一个元素替代,调整的方法是up
或者down
,因为最后一个元素和移除位置元素的parent节点或children节点的大小关系是不确定的,所以像下面这样写,Fix
方法也是一样的。
if !down(h, i, h.Len()) {
up(h, i)
}
用法参考:
https://studygolang.com/articles/12942
在go中使用堆只需要定义一个切片实现Interface
接口就好了,具体包括五个方法,即Len()
, Less()
, Swap()
, Push(x interface{})
, Pop() interface{}
。
例如下面实现了一个包含int
的最小堆:
package heap_test
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 interface{}) {
// 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() interface{} {
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 Example_intHeap() {
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
}
扩展
这里无关堆的底层实现,有一些关于go切片的知识点需要注意:
- Go语言的函数参数传递,只有值传递,没有引用传递;
- 当slice作为函数参数时,就是一个普通的结构体(包含三个成员:
len
,cap
,array
,分别表示切片长度,容量,底层数据的地址)。若直接传slice,在调用者看来,实参slice并不会被函数中的操作改变;若传的是slice的指针,在调用者看来,是会被改变原slice的。- 不管传的是slice还是slice指针,如果改变了slice底层数组的数据,会反映到实参slice的底层数据
这就是这里为什么写法上
Push()
和Pop()
方法的方法接收者是结构体指针。另外有一个知识点就是,指针类型的方法集不仅包括指针类型作为接收者的方法还包括指针类型作为接收者的方法。
这里需要注意一下Push()
和Pop()
的写法,Push()
需要做的事情是直接将新的元素append到切片的末尾,Pop()
需要做的事是弹出切片最后一个元素(在container/heap的pop实现中会先将0位置与最后一个位置的元素交换,然后对0位置的元素做sift down操作,最后调用用户自己实现的pop方法弹出末尾元素-初始堆顶元素)并修改切片内容。
刷leetcode过程发现的堆的更简便的写法:
type hp struct { sort.IntSlice } // sort.IntSlice实现了Len Less Swap方法 就不用自己写了
func (h *hp)Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(Int)) }
func (h *hp)Pop() interface{} { x := h.IntSlice[len(h.IntSlice)-1]; h.IntSlice = h.IntSlice[:len(h.IntSlice)-1]; return x }
优先级队列
下面是优先级队列实现的例子:
// This example demonstrates a priority queue built using the heap interface.
package heap_test
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 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
}
// 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 Example_priorityQueue() {
// 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
}