题目

有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 xy,且 x <= y。那么粉碎的可能结果如下:

  • 如果 x == y,那么两块石头都会被完全粉碎;
  • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x

最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。

方案一(最小堆)

  1. import heapq
  2. class Solution:
  3. def lastStoneWeight(self, stones: List[int]) -> int:
  4. stones = [-stone for stone in stones]
  5. # 由于 heapq 是最小堆,此处转化为负数
  6. heapq.heapify(stones)
  7. while len(stones) >= 2:
  8. stone_1 = -heapq.heappop(stones)
  9. stone_2 = -heapq.heappop(stones)
  10. if stone_1 == stone_2:
  11. continue
  12. heapq.heappush(stones, -abs(stone_1 - stone_2))
  13. return -stones[0] if len(stones) == 1 else 0

原文

https://leetcode-cn.com/problems/last-stone-weight/