leetcode 1046. Last Stone Weight(python)

791 阅读1分钟

描述

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.)

Example 1:

Input: [2,7,4,1,8,1]
Output: 1
Explanation: 
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.

Note:

1 <= stones.length <= 30
1 <= stones[i] <= 1000

解析

根据题意,如果 stones 的长度为 1 ,就直接返回该石头的重量。如果 stones 长度大于等于 2 ,则每一轮挑出最重的两个石头 x 和 y 进行碰撞,如果重量一样则都会被毁掉,如果不一样则只会剩下较重的石头且重量为 abs(a-b) ,等到最后如果剩下一个石头则直接返回,如果石头都被毁掉则返回 0 。按照这个思路解题很简单。

解答

class Solution(object):
    def lastStoneWeight(self, stones):
        """
        :type stones: List[int]
        :rtype: int
        """
        if (len(stones) == 1):
            return stones[0]
        if (stones.count(stones[0]) == len(stones)):
            return 0
        stones.sort(reverse=False)
        while len(stones) > 1:
            a = stones[-1]
            b = stones[-2]
            if a - b != 0:
                stones = stones[:-2] + [a - b]
            else:
                stones = stones[:-2]
            stones.sort(reverse=False)
            print(stones)
        if stones:
            return stones[0]
        return 0
        	      
		

运行结果

Runtime: 20 ms, faster than 69.57% of Python online submissions for Last Stone Weight.
Memory Usage: 13.4 MB, less than 53.09% of Python online submissions for Last Stone Weight.

解答

class Solution(object):
    def lastStoneWeight(self, stones):
        """
        :type stones: List[int]
        :rtype: int
        """
        while len(stones)>1:
            stones.append(stones.pop(stones.index(max(stones)))-stones.pop(stones.index(max(stones))))
        return stones[0]
            

运行结果

Runtime: 24 ms, faster than 41.86% of Python online submissions for Last Stone Weight.
Memory Usage: 13.2 MB, less than 95.58% of Python online submissions for Last Stone Weight.

原题链接:leetcode.com/problems/la…

您的支持是我最大的动力