在 Python 中, heapq
模块提供了一个优先级队列。
它有插入和弹出项目的方法。
您如何从队列中删除您插入的不是最低优先级的项目?
(也欢迎使用替代的其他集合来执行此操作的替代食谱)
原文由 Will 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
4 回答887 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
1 回答1.6k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
The
heapq
module uses standard Python lists as underlying data structure, so you can just use the standardlist
methodremove()
andheapify()
again after这个。请注意,这需要线性时间。您可以使用未记录的函数
heapify._siftup()
再次提高堆化的性能,但整个过程仍然是 O(n),因为list.remove()
是 O(n)。