-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathheap.go
42 lines (35 loc) · 812 Bytes
/
heap.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
package godata
import "container/heap"
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) 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 *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func PopMin(m *MinHeap) int{
if m.Len() > 0 {
heap.Init(m)
return heap.Pop(m).(int)
}
return -1
}
func PushMin(m *MinHeap,value int){
heap.Init(m)
heap.Push(m,value)
}
func TopMin(m *MinHeap)int {
heap.Init(m)
value := heap.Pop(m)
heap.Push(m,value)
return value.(int)
}