问题描述
我如何直接将输入列表添加到堆?,其中一些内置函数用于推入,获取最小值,提取最小值,但如何从堆中提取最大值。 一些功能,如..
-
heappush(heap,ele):-此函数用于将参数中提到的元素插入堆中。调整顺序,以保持堆结构。
heap = []
heapify(heap)
heappush(heap,10)
heappush(heap,30)
heappush(heap,20)
heappush(heap,400)
# printing the elements of the heap
for i in heap:
print( i,end = ' ')
print("\n")
解决方法
import heapq
heap = [] # creates an empty heap
item = [20,4,8,10,5,7,6,2,9]
for i in item:
heapq.heappush(heap,i) # pushes a new item on the heap
print('Heap obtained from heappush() : ',heap)
heapq.heapify(item) # transforms list into a heap,in-place,in linear time
print('Heap obtained from heapify() : ',item)
对于maxheap
-
heapq 实现带有后缀 _max 示例的功能:_heapify_max,_heapreplace_max等。
from _heapq import _heappop_max,_heapify_max,_heapreplace_max a = [20,9] _heapify_max(a) print('Heap obtained from _heappop_max() : ',a)
-
或者您可以将列表与-1乘以并使用minheap本身。
Then 100 becomes -100,5 becomes -5,etc.
我希望这会有所帮助。