Skip to content

Commit b925743

Browse files
Create 1046. 最后一块石头的重量.md
1 parent 4b8b954 commit b925743

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#### 1046. 最后一块石头的重量
2+
3+
难度:简单
4+
5+
---
6+
7+
有一堆石头,每块石头的重量都是正整数。
8+
9+
每一回合,从中选出两块 **最重的** 石头,然后将它们一起粉碎。假设石头的重量分别为 `x` 和 `y`,且 `x <= y`。那么粉碎的可能结果如下:
10+
11+
* 如果 `x == y`,那么两块石头都会被完全粉碎;
12+
* 如果 `x != y`,那么重量为 `x` 的石头将会完全粉碎,而重量为 `y` 的石头新重量为 `y-x`
13+
14+
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 `0`
15+
16+
**示例:**
17+
18+
```
19+
输入:[2,7,4,1,8,1]
20+
输出:1
21+
解释:
22+
先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1],
23+
再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1],
24+
接着是 2 和 1,得到 1,所以数组转换为 [1,1,1],
25+
最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
26+
```
27+
28+
**提示:**
29+
30+
* `1 <= stones.length <= 30`
31+
* `1 <= stones[i] <= 1000`
32+
33+
---
34+
35+
最大堆:
36+
37+
每次连续两次弹出堆顶元素并相减,再将相减后的值插入到堆中。
38+
39+
```Go
40+
type hp struct {
41+
sort.IntSlice
42+
}
43+
44+
func (h hp) Less(i, j int) bool {
45+
return h.IntSlice[i] > h.IntSlice[j]
46+
}
47+
48+
func (h *hp) Push(v interface{}) {
49+
h.IntSlice = append(h.IntSlice, v.(int))
50+
}
51+
52+
func (h *hp) Pop() interface{} {
53+
temp := h.IntSlice
54+
v := temp[len(temp) - 1]
55+
h.IntSlice = temp[:len(temp) - 1]
56+
return v
57+
}
58+
59+
func (h *hp) push(v int) {
60+
heap.Push(h, v)
61+
}
62+
63+
func (h *hp) pop() int {
64+
return heap.Pop(h).(int)
65+
}
66+
67+
func lastStoneWeight(stones []int) int {
68+
maxnHeap := &hp{stones}
69+
heap.Init(maxnHeap)
70+
for len(maxnHeap.IntSlice) > 1 {
71+
y := maxnHeap.pop()
72+
x := maxnHeap.pop()
73+
if y - x != 0 {
74+
maxnHeap.push(y - x)
75+
}
76+
}
77+
if len(maxnHeap.IntSlice) == 0 {
78+
return 0
79+
}
80+
return maxnHeap.pop()
81+
}
82+
```

0 commit comments

Comments
 (0)