LeetCode刷题笔记第1046题:最后一块石头的重量
想法:
通过给定的数据元素构建大顶堆,并根据题中所给限制完成最后一块石头的重量(如果存在最后一块石头)。
class Solution:
def lastStoneWeight(self, stones) :
def sift_down(stones, parent):
val = stones[parent]
while parent <<1 <len(stones):
child = parent << 1
if child|1 < len(stones) and stones[child] <stones[child|1]:
child = child | 1
if val< stones[child]:
stones[parent] = stones[child]
parent = child
else:
break
stones[parent] = val
#最大堆
stones.insert(0,'dummy')
# print(stones)
# print(len(stones))
parent = (len(stones)-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]