# Median of Data Stream

### 描述​

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

• void addNum(int num) - Add a integer number from the data stream to the data structure.
• double findMedian() - Return the median of all elements so far.

Example:

findMedian() -> 1.5
findMedian() -> 2

1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

### 代码​

# Median of Data Stream# Using two heaps# Overall Space Complexity: O(n)class MedianFinder:    def __init__(self):        self.min_heap = []        self.max_heap = []    def addNum(self, num: int) -> None:        """Time Complexity: O(logn)"""        root = heapq.heappushpop(self.max_heap,-num)        heapq.heappush(self.min_heap, -root)        while len(self.max_heap) < len(self.min_heap):            root = heapq.heappop(self.min_heap)            heapq.heappush(self.max_heap, -root)    def findMedian(self) -> float:        """Time Complexity: O(1)"""        if len(self.max_heap) == len(self.min_heap):            return (-self.max_heap[0]  + self.min_heap[0])/2        else:            return -self.max_heap[0]