python内的heapq提供heappush,heappop两个方法,然而对于 删除 中间的某个参数没有给出相应的方法:
from heapq import heappush, heappop, _siftdown, _siftup
# heap data structure, (value, key), value is used for sorting and key used for identifying
def heapdelete(heap,i):
nodeValue = heap[i];leafValue = heap[-1];
if nodeValue == leafValue:
heap.pop(-1)
elif nodeValue <= leafValue: # similar to heappop
heap[i], heap[-1] = heap[-1], heap[i]
minimumValue = heap.pop(-1)
if heap != []:
_siftup(heap, i)
else: # similar to heappush
heap[i], heap[-1] = heap[-1], heap[i]
minimumValue = heap.pop(-1)
_siftdown(heap, 0, i)
本文介绍如何在Python的heapq模块中实现自定义元素的删除功能,通过定义heapdelete函数,利用heapq的_siftdown和_siftup方法来调整堆结构,以实现对指定元素的有效移除。
1196

被折叠的 条评论
为什么被折叠?



