想法:
通过给定的数据元素构建大顶堆,并根据题中所给限制完成最后一块石头的重量(如果存在最后一块石头)。
class Solution:
def lastStoneWeight(self, stones) :
def sift_down(stones, parent):
val = stones[parent]
while parent <<1 >1
for i in range(parent,0,-1):
sift_down(stones,i)
while len(stones)>2:
stone1 = stones[1]
stones[1]=stones.pop(-1)
sift_down(stones,1)
stone2 = stones[1]
#此时stones里除了占位符,至少还有一块石头。
if stone2 == stone1:
if len(stones) >2:
stones[1] = stones.pop(-1)
sift_down(stones,1)
else:
stones.pop(-1)
else:
stones[1] = stone1 - stone2
sift_down(stones,1)
stones.pop(0)
if stones == []:
return 0
else:
return stones[0]



