Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f7fd585

Browse files
committed
976 finish
1 parent 073c25b commit f7fd585

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed
Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,50 @@
11
package problem0976
22

3-
import "sort"
3+
import "container/heap"
44

55
func largestPerimeter(A []int) int {
66
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)
913
for i := size - 3; i >= 0; i-- {
10-
c := A[i]
14+
c := heap.Pop(&h).(int)
1115
if a < b+c {
1216
return a + b + c
1317
}
1418
a, b = b, c
1519
}
1620
return 0
1721
}
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+
}

0 commit comments

Comments
 (0)