Skip to content

Commit 9a2464d

Browse files
committed
python max heap
1 parent f742626 commit 9a2464d

File tree

1 file changed

+39
-0
lines changed
  • docs/19_python内置常用算法和数据结构

1 file changed

+39
-0
lines changed

docs/19_python内置常用算法和数据结构/builtins.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,45 @@ def test_heap_item():
195195
print(heapq.heappop(pq))
196196
```
197197

198+
# python 如何实现最大堆
199+
python自带了heapq 模块实现了最小堆(min-heaq),但是如果想要实现最大堆(max-heap),有几种实现方式:
200+
201+
1. 对放入的数字取反。比如 10 放入 -10 ,然后取出来的时候再取反。个人倾向于这种,可以自己封装一个类防止来回取反搞晕
202+
2. 直接根据 heapq 模块的函数封装几个最大堆的函数,也是通过取反实现
203+
3. 新建一个对象重写 `__lt__` 魔术方法。这种方式也可以,但是重写魔术方法修改了语义不太好(个人不推荐)
204+
205+
```py
206+
# 方法1:封装一个 max heap 类
207+
import heapq
208+
class MaxHeap:
209+
"""
210+
https://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python
211+
"""
212+
def __init__(self, capacity):
213+
self.capacity = capacity
214+
self.minheap = []
215+
216+
def push(self, val):
217+
heapq.heappush(self.minheap, -val) # push取反后的数字, 1 -> -1
218+
219+
def pop(self):
220+
val = heapq.heappop(self.minheap)
221+
return -val # 拿出来的数字再取反
222+
223+
def max(self):
224+
return -self.minheap[0] # min-heap 的数组最小值是 m[0],最大值取反
225+
226+
# 方法2: 重新定几个新的 max-heap 方法
227+
import heapq
228+
def maxheappush(h, item):
229+
return heapq.heappush(h, -item)
230+
231+
def maxheappop(h):
232+
return -heapq.heappop(h)
233+
234+
def maxheapval(h):
235+
return -h[0]
236+
``````
198237

199238
# lru_cache/cache 优化记忆化搜索
200239

0 commit comments

Comments
 (0)