File tree 3 files changed +92
-0
lines changed
3 files changed +92
-0
lines changed Original file line number Diff line number Diff line change 9
9
10
10
### leet_code [ leet_code刷题]
11
11
1: leet_code刷题
12
+
13
+ ### heap [ 堆]
14
+ 1: max_heap_test 大顶推
15
+ 2: min_heap_test 小顶堆
12
16
13
17
### linked_list [ 链表]
14
18
1: cycle_list 循环链表
Original file line number Diff line number Diff line change
1
+ package heap
2
+
3
+ import (
4
+ "container/heap"
5
+ "fmt"
6
+ "testing"
7
+ )
8
+
9
+ type MaxHeap []int
10
+
11
+ func (m MaxHeap ) Len () int {
12
+ return len (m )
13
+ }
14
+
15
+ func (m MaxHeap ) Less (i , j int ) bool {
16
+ return m [i ] > m [j ]
17
+ }
18
+
19
+ func (m MaxHeap ) Swap (i , j int ) {
20
+ m [i ], m [j ] = m [j ], m [i ]
21
+ }
22
+
23
+ func (m * MaxHeap ) Push (x interface {}) {
24
+ * m = append (* m , x .(int ))
25
+ }
26
+
27
+ func (m * MaxHeap ) Pop () interface {} {
28
+ old := * m
29
+ n := len (old )
30
+ x := old [n - 1 ]
31
+ * m = old [0 : n - 1 ]
32
+ return x
33
+ }
34
+
35
+ func TestMaxHeap (t * testing.T ) {
36
+ m := & MaxHeap {
37
+ 2 , 10 , 5 , 9 , 12 , 7 , 3 ,
38
+ }
39
+ heap .Init (m )
40
+ for m .Len () > 0 {
41
+ fmt .Printf ("%d " , heap .Pop (m ))
42
+ }
43
+
44
+ }
Original file line number Diff line number Diff line change
1
+ package heap
2
+
3
+ import (
4
+ "container/heap"
5
+ "fmt"
6
+ "testing"
7
+ )
8
+
9
+ type MinHeap []int
10
+
11
+ func (m MinHeap ) Len () int {
12
+ return len (m )
13
+ }
14
+
15
+ func (m MinHeap ) Less (i , j int ) bool {
16
+ return m [i ] < m [j ]
17
+ }
18
+
19
+ func (m MinHeap ) Swap (i , j int ) {
20
+ m [i ], m [j ] = m [j ], m [i ]
21
+ }
22
+
23
+ func (m * MinHeap ) Push (x interface {}) {
24
+ * m = append (* m , x .(int ))
25
+ }
26
+
27
+ func (m * MinHeap ) Pop () interface {} {
28
+ old := * m
29
+ n := len (old )
30
+ x := old [n - 1 ]
31
+ * m = old [0 : n - 1 ]
32
+ return x
33
+ }
34
+
35
+ func TestMinHeap (t * testing.T ) {
36
+ m := & MinHeap {
37
+ 2 , 10 , 5 , 9 , 12 , 7 , 3 ,
38
+ }
39
+ heap .Init (m )
40
+ for m .Len () > 0 {
41
+ fmt .Printf ("%d " , heap .Pop (m ))
42
+ }
43
+
44
+ }
You can’t perform that action at this time.
0 commit comments