Leetcode: 295. Find Median from Data Stream
- Pattern: Answer query on sorted data. Keep a sorted list of the numbers and compute the median using it. Time complexity is \(O(n \log n)\) and space is \(O(n)\).
from sortedcontainers import SortedList class MedianFinder: def __init__(self): self.s = SortedList() def addNum(self, num: int) -> None: self.s.add(num) def findMedian(self) -> float: N = len(self.s) if N % 2 == 0: return (self.s[N // 2] + self.s[N // 2 - 1]) / 2 return self.s[N // 2] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()