LeetCode 1046 Last Stone Weight (Python)

Posted by 小明MaxMing on April 26, 2020

题目

We have a collection of stones, each stone has a positive integer weight.

Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:

  • If x == y, both stones are totally destroyed;
  • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)

解题思路

使用优先队列,将石子从放到优先队列(大头)中,每次pop出来最大的两个,做差(如果非0)将绝对值加回队里中,直到结束

代码

import heapq
class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        stones = [-s for s in stones]
        heapq.heapify(stones)
        while len(stones) >= 2:
            s1 = heapq.heappop(stones)
            s2 = heapq.heappop(stones)
            if s1 != s2:
                heapq.heappush(stones, s1 - s2)
        return -stones[0] if stones else 0

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅