Skip to content

Commit 4b8b954

Browse files
Create 堆.md
1 parent 2f9a900 commit 4b8b954

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Heap/堆.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Go 语言:
2+
3+
```go
4+
package main
5+
6+
import (
7+
"container/heap"
8+
"fmt"
9+
"sort"
10+
)
11+
12+
type heap2 struct {
13+
sort.IntSlice
14+
}
15+
16+
func (h heap2) Less(i, j int) bool { // 最小堆:h.IntSlice[i] < h.IntSlice[j];最大堆:h.IntSlice[i] > h.IntSlice[j];
17+
return h.IntSlice[i] > h.IntSlice[j]
18+
}
19+
20+
func (h *heap2) Push(v interface{}) {
21+
h.IntSlice = append(h.IntSlice, v.(int))
22+
}
23+
24+
func (h *heap2) Pop() interface{} {
25+
temp := h.IntSlice
26+
v := temp[len(temp)-1]
27+
h.IntSlice = temp[:len(temp)-1]
28+
return v
29+
}
30+
31+
func (h *heap2) push(v int) {
32+
heap.Push(h, v)
33+
}
34+
35+
func (h *heap2) pop() int {
36+
return heap.Pop(h).(int)
37+
}
38+
39+
func main() {
40+
q := &heap2{[]int{3, 4, 1, 2, 4, 3}}
41+
heap.Init(q)
42+
fmt.Println(q)
43+
}
44+
45+
```
46+

0 commit comments

Comments
 (0)