堆本质是一个完全二叉树,分为大根堆和小根堆,大根堆每个结点的值都大于它的孩子的值,小根堆相反,每个结点的值都小于它的孩子的值
heapq是python的标准库,用于维护堆,非常方便
heapq库常用的几个函数
heapify(list),把列表list转换为小根堆
heappush(heap, item),将item的值加入到heap中,保持堆性质不变
heappop(heap),弹出并返回heap的堆顶(即最小值),保持堆的不变
heapq.nlargest(n,heap),返回一个列表,为heap的前n个最大值
heapq.nsmallest(n,heap),返回一个列表,为heap的前n个最小值
示例用法如下
import heapq
heap = [14, 6, 2, 8, 12, 11, 23]
heapq.heapify(heap)
print(heap)
heapq.heappush(heap, 5)
print(heap)
print(heapq.heappop(heap))
import heapq
heap = [14, 6, 2, 8, 12, 11, 23]
print(heapq.nlargest(3, heap))
print(heapq.nsmallest(3, heap))
heapq只能构造小根堆,但是可以通过给数加符号的方法构造大根堆
import heapq
a = [14, 6, 2, 8, 12, 11, 23, 18]
heap = []
for i in range(len(a)):
heapq.heappush(heap, -a[i]) # 将所有值的负数构造一个小根堆
print(-heapq.heappop(heap)) # 最后输出的时候加负号即可
结果