对于列表,heappop将弹出前面的元素.从列表前面删除元素的时间复杂度为O(n).
我想念什么吗? 最佳答案 一个heappop()重新排列列表中的log(n)元素,这样它就不必移动每个元素.
这很容易看出:
>>> from random import randrange
>>> from heapq import heapify, heappop
>>> h = [randrange(1000) for i in range(15)]
>>> heapify(h)
>>> h
[80, 126, 248, 336, 335, 413, 595, 405, 470, 592, 540, 566, 484, 970, 963]
>>> heappop(h)
80
>>> h
[126, 335, 248, 336, 540, 413, 595, 405, 470, 592, 963, 566, 484, 970]
>>> # ^----^---------^----^----^----^----^---------^----^----^--- elements that didn't move
请注意,弹出操作没有移动大多数元素(例如248在heappop之前和之后处于相同位置).