最小堆
"""
(1)堆的数据要基于链表(List)进行操作(堆中的数据是基于链表进行操作)。
(2)堆直接基于链表操作,不再开辟新的存储空间。
(3)堆头永远都是最小的值。
(4)堆的检索是根据中序遍历方式:根节点 --> 左节点 -->右节点
"""
import heapq
# (1)创建一个空堆,并加入数据
heap = []
for item in [2, 3, 1, 4]:
heapq.heappush(heap, item)
print(heap) # 输出 [1, 3, 2, 4]
# (2)根据链表构建一个堆 --> heapify
l = [2, 3, 1, 4]
heapq.heapify(l)
print(l) # 输出 [1, 3, 2, 4]
# (2)向堆中追加元素 -->heappush
heapq.heappush(l, -10)
print(l) # 输出 [-10, 1, 2, 4, 3]
# (3) 弹出堆头(返回堆头之后堆再进行翻转,堆头保持最小值) -->heappop
print(heapq.heappop(l)) # 输出 -10
print(l) # 输出 [1, 3, 2, 4]
print(heapq.heappop(l)) # 输出 1
print(l) # 输出 [2, 3, 4]
# (4) 替换第一个元素,并构建堆 --> heapreplace
l = [2, 3, 1, 4]
print(heapq.heapreplace(l, 100)) # 输出 2
print(l) # 输出 [1, 3, 100, 4]
# (5)合并多个链表 --> merge
l = [1, 3, 2]
l2 = [5, 2, 3]
l3 = [9, 2, 3, 1]
print(list(heapq.merge(l, l2, l3))) # 输出 [1, 3, 2, 5, 2, 3, 9, 2, 3, 1]
# (6)多路归并 --> merge
# 对每一个链表进行排序,再对排序后的列表进行合并
print(list(heapq.merge(sorted(l), sorted(l2), sorted(l3))))
# (7)返回最大的元素 --> nlargest
l = [2, 3, 1, 4]
print(heapq.nlargest(2, l)) # 输出 [4, 3]
# (8)返回最小的元素 --> nsmallest
l = [2, 3, 1, 4]
print(heapq.nsmallest(2, l)) # 输出 [1, 2]
# (9)向堆中追加一个数据,再弹出堆头(弹出后堆不会发生翻转) --> heappushpop
l = [2, 3, 1, 4]
print(heapq.heappushpop(l, -10)) # 输出 -10
print(l) # 输出 [2, 3, 1, 4]
最后更新于
这有帮助吗?