Find Median from Data Stream
Examples
Example 1:
Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"]
[[],[1],[2],[],[3],[]]
Output: [null, null, null, 1.5, null, 2.0]
Explanation:
Example 1:
Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"]
[[],[1],[2],[],[3],[]]
Output: [null, null, null, 1.5, null, 2.0]
Explanation:
The median is the middle value in a sorted list of integers. For lists of even length, there is no middle value, so the median is the mean of the two middle values.
For example:
arr = [1,2,3], the median is 2.arr = [1,2], the median is (1 + 2) / 2 = 1.5Implement 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.MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // return 1.5
medianFinder.addNum(3); // arr = [1, 2, 3]
medianFinder.findMedian(); // return 2.0
-100,000 <= num <= 100,000findMedian will only be called after adding at least one integer to the data structure.Maintain two heaps: a max-heap for the lower half and a min-heap for the upper half. When adding a number, push it to the max-heap, move the max to the min-heap, then rebalance so the max-heap has either the same size or one extra element. The median is the top of the max-heap for odd counts or the average of both tops for even counts.
The max-heap stores the largest element of the lower half and the min-heap stores the smallest element of the upper half. Rebalancing keeps the halves sized correctly, so the median is always determined by the heap tops. This holds after every insertion.
O(log n) per add, O(1) per median queryO(n)class MedianFinder:
def __init__(self):
self.small = [] # max-heap (store negatives)
self.large = [] # min-heap
def addNum(self, num: int) -> None:
heapq.heappush(self.small, -num)
heapq.heappush(self.large, -heapq.heappop(self.small))
if len(self.large) > len(self.small):
heapq.heappush(self.small, -heapq.heappop(self.large))
def findMedian(self) -> float:
if len(self.small) > len(self.large):
return float(-self.small[0])
return (-self.small[0] + self.large[0]) / 2.0