forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.go
54 lines (44 loc) · 1.2 KB
/
PriorityQueue.go
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package structures
// This example demonstrates a priority queue built using the heap interface.
import (
"container/heap"
)
// entry 是 priorityQueue 中的元素
type entry struct {
key string
priority int
// index 是 entry 在 heap 中的索引号
// entry 加入 Priority Queue 后, Priority 会变化时,很有用
// 如果 entry.priority 一直不变的话,可以删除 index
index int
}
// PQ implements heap.Interface and holds entries.
type PQ []*entry
func (pq PQ) Len() int { return len(pq) }
func (pq PQ) Less(i, j int) bool {
return pq[i].priority < pq[j].priority
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
// Push 往 pq 中放 entry
func (pq *PQ) Push(x interface{}) {
temp := x.(*entry)
temp.index = len(*pq)
*pq = append(*pq, temp)
}
// Pop 从 pq 中取出最优先的 entry
func (pq *PQ) Pop() interface{} {
temp := (*pq)[len(*pq)-1]
temp.index = -1 // for safety
*pq = (*pq)[0 : len(*pq)-1]
return temp
}
// update modifies the priority and value of an entry in the queue.
func (pq *PQ) update(entry *entry, value string, priority int) {
entry.key = value
entry.priority = priority
heap.Fix(pq, entry.index)
}