smj007

find median from data stream

Aug 9th, 2025
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | Source Code | 0 0
  1. import heapq
  2.  
  3. class MedianFinder:
  4.     def __init__(self):
  5.         self.minheap = []  # right half (min-heap)
  6.         self.maxheap = []  # left half  (max-heap via negatives)
  7.  
  8.     def addNum(self, num: int) -> None:
  9.         # push to maxheap (as negative to simulate max-heap)
  10.         heapq.heappush(self.maxheap, -num)
  11.  
  12.         # ensure order: every item in maxheap <= every item in minheap
  13.         heapq.heappush(self.minheap, -heapq.heappop(self.maxheap))
  14.  
  15.         # balance sizes: maxheap can have one extra
  16.         if len(self.minheap) > len(self.maxheap):
  17.             heapq.heappush(self.maxheap, -heapq.heappop(self.minheap))
  18.  
  19.     def findMedian(self) -> float:
  20.         if len(self.maxheap) > len(self.minheap):
  21.             return float(-self.maxheap[0])
  22.         return (-self.maxheap[0] + self.minheap[0]) / 2.0
Advertisement
Add Comment
Please, Sign In to add comment