python中的堆
- python中没有独立的堆这个数据结构,但是有一个包含堆操作函数的模块(heapq)
函数 | 功能 |
---|---|
heappush(heap, x) | 将x压入堆中 |
heappop(heap) | 从堆中弹出最小元素 |
heapify(heap) | 让列表具备堆特征 |
heapreplace(heap, x) | 弹出最小元素,并将x压入堆中 |
nlargest(n, iter) | 返回iter中n个最大的元素 |
nsmallest(n, iter) | 返回iter中n个最小的元素 |
- 堆(heap)是一种优先队列。优先队列让你能够以任意顺序添加对象,并随时找出删除最小的元素
from heapq import *
from random import shuffle
# a = list(range(10))
a = [0,1,2,3,4,5,6,7,8,9]
shuffle(a)
heap = []
for i in a:
heappush(heap, i)
print(a) # [8, 6, 7, 3, 5, 4, 2, 0, 1, 9]
print(heap) # [0, 1, 3, 2, 6, 7, 4, 8, 5, 9]
元素的排列顺序并不像看起来那么随意,虽然不是严格排序的,但必须保证:位置 i 处的