Problem
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
- For example, for arr = [2,3,4], the median is 3.
- For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
- MedianFinder() initializes the MedianFinder object.
- void addNum(int num) adds the integer num from the data stream to the data structure.
- double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
Algorithm
Use two heap to save the data, each save half of the total data.
Code
python3
class MedianFinder:
def __init__(self):
self.small_heap = []
self.large_heap = []
self.heap_size = 0
def addNum(self, num: int) -> None:
heapq.heappush(self.small_heap, -num)
if self.large_heap and (self.large_heap[0] > -self.large_heap[0]):
heapq.heappush(self.large_heap, -heapq.heappop(self.small_heap))
heapq.heappush(self.small_heap, -heapq.heappop(self.large_heap))
if self.heap_size % 2 == 0:
heapq.heappush(self.large_heap, -heapq.heappop(self.small_heap))
self.heap_size += 1
def findMedian(self) -> float:
if not self.heap_size:
return None
if self.heap_size % 2 == 0:
return (self.large_heap[0] - self.small_heap[0]) / 2
else:
return self.large_heap[0]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()