File tree Expand file tree Collapse file tree 1 file changed +37
-4
lines changed
Algorithms/0976.largest-perimeter-triangle Expand file tree Collapse file tree 1 file changed +37
-4
lines changed Original file line number Diff line number Diff line change 1
1
package problem0976
2
2
3
- import "sort "
3
+ import "container/heap "
4
4
5
5
func largestPerimeter (A []int ) int {
6
6
size := len (A )
7
- sort .Ints (A )
8
- a , b := A [size - 1 ], A [size - 2 ]
7
+ h := intHeap (A )
8
+
9
+ heap .Init (& h )
10
+
11
+ a := heap .Pop (& h ).(int )
12
+ b := heap .Pop (& h ).(int )
9
13
for i := size - 3 ; i >= 0 ; i -- {
10
- c := A [ i ]
14
+ c := heap . Pop ( & h ).( int )
11
15
if a < b + c {
12
16
return a + b + c
13
17
}
14
18
a , b = b , c
15
19
}
16
20
return 0
17
21
}
22
+
23
+ // intHeap 实现了 heap 的接口
24
+ type intHeap []int
25
+
26
+ func (h intHeap ) Len () int {
27
+ return len (h )
28
+ }
29
+
30
+ func (h intHeap ) Less (i , j int ) bool {
31
+ return h [i ] > h [j ] // NOTICE: Max is at the top
32
+ }
33
+
34
+ func (h intHeap ) Swap (i , j int ) {
35
+ h [i ], h [j ] = h [j ], h [i ]
36
+ }
37
+
38
+ func (h * intHeap ) Push (x interface {}) {
39
+ // Push 使用 *h,是因为
40
+ // Push 增加了 h 的长度
41
+ // *h = append(*h, x.(int))
42
+ }
43
+
44
+ func (h * intHeap ) Pop () interface {} {
45
+ // Pop 使用 *h ,是因为
46
+ // Pop 减短了 h 的长度
47
+ res := (* h )[len (* h )- 1 ]
48
+ * h = (* h )[:len (* h )- 1 ]
49
+ return res
50
+ }
You can’t perform that action at this time.
0 commit comments