我在网上搜索了Python中MinHeap和Maxheap的实现。
import heapq
class MinHeap:
def __init__(self):
self.heap = []
def push(self, item):
heapq.heappush(self.heap, item)
def pop(self):
return heapq.heappop(self.h)
def __getitem__(self, item):
return self.heap[item]
def __len__(self):
return len(self.h)
class MaxHeap(MinHeap):
def push(self, item):
heapq.heappush(self.heap, Comparator(item))
def pop(self):
return heapq.heappop(self.h)
def __getitem__(self, i):
return self.heap[i].val
class Comparator:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > self.other
def __eq__(self, other):
return self.val == self.other
def __str__(self):
return str(self.val)
现在我需要为这两个类添加一个peek方法。在它的当前实现中,我可以弹出并推回。但我的问题是,有没有更好的方法来做到这一点。 O(1)时间内的东西。
答案 0 :(得分:2)
这些类基于Python的heapq
结构,该结构构建在标准的Python列表中。 minheap中的最小项目和maxheap中的最大项目位于索引零处。所以回来
self.heap[0]
如果堆为空,那将导致错误,但这可能就是你想要的。