有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
【简单】
【分析】直接调用的排序函数。。。。。
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
if len(stones)==0:
return 0
stones=sorted(stones)
while len(stones)>1:
y=stones.pop()
x=stones.pop()
if x!=y:
stones.append(y-x)
stones=sorted(stones)
return 0 if len(stones)==0 else stones[0]
【补充——堆和堆排序】
堆的结构是完全二叉树的结构,但是是利用数组来实现的。
堆中任意结点iii的父结点是⌊i−12⌋\left \lfloor \frac{i-1}{2} \right \rfloor⌊2i−1⌋,左右子结点分别是2i+1,2i+22i+1,2i+22i+1,2i+2.
堆的操作(以大根堆为例):
- 上浮shift up:若当前结点iii大于其父结点(若父结点存在)的值,则当前结点与父结点交换位置,同时iii=原父结点的索引。
- 下沉shift down:若当前结点iii小于左右孩子(若孩子存在)的值,则与孩子中最大的那个交换位置,同时iii=原被交换的那个孩子的索引。
- 弹出 pop:取出根节点的值,交换首尾结点的位置,根节点下沉。
- 插入 push:在数组后面插入新的结点,尾节点上浮。
以本题中的stones为实例,做一个从大到小的堆排序(不涉及本题的解,只单纯作一次堆排序的实践)。
def shift_up(i,max_heap):
"""
:type(i) int 当前结点的索引
"""
while int((i-1)/2)>=0:
parent=int((i-1)/2)
if max_heap[parent]<max_heap[i]:
tmp=max_heap[parent]
max_heap[parent]=max_heap[i]
max_heap[i]=tmp
i=parent
else:break
return max_heap
def push(x,max_heap):
"""
:type x 表示插入的值
"""
max_heap.append(x)
max_heap=shift_up(len(max_heap)-1,max_heap)
return max_heap
stones=[2,26,5,77,1,61,11,59,15,48,19] ##实例
#建堆
for i in range(len(stones)):
if i==0:
max_heap=[stones[0]]
else:
max_heap=push(stones[i],max_heap)
#自下向上建堆
def shift_down(i,max_heap):
while 2*i+1<len(max_heap):
index=2*i+1
if index+1<len(max_heap) and max_heap[index+1]>max_heap[index]:
index+=1
if max_heap[index]>max_heap[i]:
tmp=max_heap[index]
max_heap[index]=max_heap[i]
max_heap[i]=tmp
i=index
else:break
return max_heap
def pop(max_heap):
res=max_heap[0]
max_heap[0]=max_heap.pop()
max_heap=shift_down(0,max_heap)
return res,max_heap
#堆排序,每次弹出根结点:
res=[]
while len(max_heap)>1:
tmp_res,max_heap=pop(max_heap)
res.append(tmp_res)
res.append(max_heap[0])
print(res)