08. heap
需要实现 heap.Interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | package main
import "container/heap"
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) 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) { *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
}
func main() {
h := &IntHeap{2, 1, 5}
heap.Init(h)
heap.Push(h, 3)
minv := heap.Pop(h)
fmt.Println(minv) // 5
}
|
// cpp 不语,只是敲了一行
priority_queue<int> heap;