forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1167.go
More file actions
38 lines (31 loc) · 680 Bytes
/
Copy path1167.go
File metadata and controls
38 lines (31 loc) · 680 Bytes
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
type IntHeap []int
func (h IntHeap) Len() int {
return len(h)
}
func (h IntHeap) Less(i, j int) bool {
return h[i] < h[j]
}
func (h IntHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *IntHeap) Pop() interface{} {
x := (*h)[(*h).Len()-1]
*h = (*h)[:(*h).Len()-1]
return x
}
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func connectSticks(sticks []int) int {
h := new(IntHeap)
for _, v := range sticks {
heap.Push(h, v)
}
res := 0
for len(*h) > 1 {
a, b := heap.Pop(h).(int), heap.Pop(h).(int)
res += a + b
heap.Push(h, int(a) + int(b))
}
return res
}