题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个一维数组,当作一堆石头重量,每次选两个最重的碰,将两个石头之差放回去,求最后剩下的一个石头重量(没有就0)

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
for i in range(len(stones)):
stones[i] = -stones[i]
heapify(stones)
while stones and len(stones) > 1:
# print(stones)
x = heappop(stones)
y = heappop(stones)
d = abs(x-y)
if d != 0:
heappush(stones, -d)
return 0 if not stones or len(stones)==0 else -heappop(stones)