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
| // @Title: 最后一块石头的重量 (Last Stone Weight)
// @Author: 15816537946@163.com
// @Date: 2020-12-30 23:38:27
// @Runtime: 0 ms
// @Memory: 2 MB
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{} {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
func lastStoneWeight(stones []int) int {
q := &hp{stones}
heap.Init(q)
for q.Len() > 1 {
x, y := q.pop(), q.pop()
if x > y {
q.push(x - y)
}
}
if q.Len() > 0 {
return q.IntSlice[0]
}
return 0
}
|