@Author: liuyangly1
@Date : 2021-07-07 21:59:18
@Blog : https://blog.csdn.net/liuyang_1106
@Github: https://github.com/liuyangly1
@Email : 522927317@qq.com
堆类型heapq
- 默认是最小堆。
- 最小堆,树种各个父节点的值总是小于或等于任何一个子节点的值。
- 一般使用二叉堆来实现优先级队列,它的内部调整算法复杂度为logN。
1. 初始化 heapq.heapify(list)
- 将列表转换为堆。
>>> import heapq
>>> x = [1,2,3,5,1,5,8,9,6]
>>> heapq.heapify(x)
>>> x
[1, 1, 3, 5, 2, 5, 8, 9, 6]
2. 添加 heapq.heappush(heap, item)
- heap为定义堆,item增加的元素。
>>> import heapq
>>> x = []
>>> heapq.heappush(x, 2)
>>> x
[2]
3. 弹出 heapq.heappop(heap)
- 删除并返回最小值,因为堆的特征是heap[0]永远是最小的元素,所以一般都是删除第一个元素。
>>> x = [1, 1, 3, 5, 2, 5, 8, 9, 6]
heapq.heapify(x)
>>> heapq.heappop(x)
1
>>> x
[1, 2, 3, 5, 6, 5, 8, 9]