python 堆
在python中,使用 \(heapq\) 库来实现堆:
import heapq
堆的初始化:直接初始化一个空列表即可。
heap = []
将给定列表初始化成小根堆,可以使用 \(heapify\) 函数:
a = [1, 3, 2, 4, 6, 5]
heapq.heapify(a)
初始化默认为小根堆,若想改成大根堆,可以通过插入相反数来实现降序排序。
往堆中加入元素:\(heappush\) 函数:
heapq.heappush(heap, 2)
弹出堆顶:\(heappop\) 函数:
x = heappop(heap)
访问堆顶元素(不弹出):直接下标访问即可
heap[0]
提取堆中的前 \(n\) 大/小:\(nlargest/nsmallest\) 函数:
heap = [4, 2, 1, 5, 6, 3]
heapq.heapify(heap)
print(heapq.nlargest(2, heap)) # [6, 5]
print(heapq.nsmallest(3, heap)) # [1, 2, 3]