有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x
和 y
,且 x <= y
。那么粉碎的可能结果如下:
- 如果
x == y
,那么两块石头都会被完全粉碎; - 如果
x != y
,那么重量为x
的石头将会完全粉碎,而重量为y
的石头新重量为y-x
。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0
。
1046. 最后一块石头的重量 – 力扣(Leetcode)

思路:
不断的排序,然后按照题意消解,最后返回就行了。
python3实现:
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# 先按顺序排列,再按题意消解,最后返回结果
while len(stones) >= 2:
stones.sort(reverse=True)
print(stones)
one = stones[0]
two = stones[1]
if one - two == 0:
stones.pop(1)
stones.pop(0)
else:
stones[0] = one - two
stones.pop(1)
if len(stones) == 0:
return 0
else:
return stones[0]

知识点:
python3中,用来删除列表指定索引的元素,用 列表.pop(索引),这道题注意删除索引的顺序。
