Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import heapq
- class MedianFinder:
- def __init__(self):
- self.minheap = [] # right half (min-heap)
- self.maxheap = [] # left half (max-heap via negatives)
- def addNum(self, num: int) -> None:
- # push to maxheap (as negative to simulate max-heap)
- heapq.heappush(self.maxheap, -num)
- # ensure order: every item in maxheap <= every item in minheap
- heapq.heappush(self.minheap, -heapq.heappop(self.maxheap))
- # balance sizes: maxheap can have one extra
- if len(self.minheap) > len(self.maxheap):
- heapq.heappush(self.maxheap, -heapq.heappop(self.minheap))
- def findMedian(self) -> float:
- if len(self.maxheap) > len(self.minheap):
- return float(-self.maxheap[0])
- return (-self.maxheap[0] + self.minheap[0]) / 2.0
Advertisement
Add Comment
Please, Sign In to add comment