heapq
是python3中的一个库,它使用了小根堆(即堆首元素最小)。
1 创建
方法1:通过heapq.heapify(nums)
将列表类型的变量nums变为小根堆类型。
示例代码如下,
import heapq
nums = [1, 3, 5, 2, 4, 6]
heapq.heapify(nums)
print(f'nums = {nums}')
#依次弹出堆首
while len(nums):
x = heapq.heappop(nums)
print(x)
结果为,
nums = [1, 2, 5, 3, 4, 6]
1
2
3
4
5
6
方法2:通过heapq.heappush(h, x)
将元素x
推入堆h
中,示例代码如下,
import heapq
nums = [1, 3, 5, 2, 4, 6]
h = []
for x in nums:
heapq.heappush(h, x)
print(f'h = {h}')
#依次弹出堆首
while len(h):
x = heapq.heappop(h)
print(x)
结果为,
h = [1, 2, 5, 3, 4, 6]
1
2
3
4
5
6
2 取堆首元素
h[0]
返回堆首元素,示例代码如下,
import heapq
nums = [3, 1, 5, 2, 4, 6]
heapq.heapify(nums)
print(f'nums[0] = {nums[0]}')
结果为,
nums[0] = 1
3 返回堆首元素并弹出
heapq.heappop(h)
返回堆首元素并弹出,示例代码如下,
import heapq
nums = [3, 1, 5, 2, 4, 6]
heapq.heapify(nums)
x = heapq.heappop(nums)
print(f'nums = {nums}')
结果为,
nums = [2, 3, 5, 6, 4]