天天看点

【leetcode-python-24】1046. 最后一块石头的重量渣渣原始版(59.09%)参考大佬版(59.09%)

【leetcode-python-24】1046. 最后一块石头的重量

  • 渣渣原始版(59.09%)
  • 参考大佬版(59.09%)

leetcode 1046. 最后一块石头的重量

渣渣原始版(59.09%)

先排序然后再一个一个比对。

class Solution(object):
    def lastStoneWeight(self, stones):
        """
        :type stones: List[int]
        :rtype: int
        """
        if not stones:
            return 0
        stones.sort(reverse=True)
        while len(stones) > 1:
            x = stones[0]-stones[1]
            stones.pop(0)
            stones.pop(0)
            for i in range(len(stones)):
                if x >stones[i]:
                    stones.insert(i,x)
                    break
            else:
                stones.append(x)
          
        return stones[0]
           

下面这个理论上好点,毕竟没有reverse,而且是直接pop的。

class Solution(object):
    def lastStoneWeight(self, stones):
        """
        :type stones: List[int]
        :rtype: int
        """
        if not stones:
            return 0
            
        stones.sort()
        while len(stones) > 1:
            x = stones.pop()-stones.pop()
            for i in range(len(stones)):
                if x <stones[i]:
                    stones.insert(i,x)
                    break
            else:
                stones.append(x)
          
        return stones[0]
           

参考大佬版(59.09%)

每次重新sort。

注:参考题解区天道妖星思路。

class Solution(object):
    def lastStoneWeight(self, stones):
        """
        :type stones: List[int]
        :rtype: int
        """
        if not stones:
            return 0
        
        while len(stones) >= 2:
            stones.sort()
            stones.append(stones.pop()-stones.pop())

        return stones[0]        
           

新手入坑,多多包涵~~