295 Find Median from Data Stream

1. Question

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.
Examples:
[2,3,4], the median is3
[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.
For example:
1
addNum(1)
2
addNum(2)
3
findMedian() -> 1.5
4
addNum(3)
5
findMedian() -> 2
Copied!

2. Implementation

(1) Heap
1
class MedianFinder {
2
private PriorityQueue<Integer> minHeap;
3
private PriorityQueue<Integer> maxHeap;
4
5
/** initialize your data structure here. */
6
public MedianFinder() {
7
minHeap = new PriorityQueue<>();
8
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
9
}
10
11
public void addNum(int num) {
12
maxHeap.add(num);
13
minHeap.add(maxHeap.remove());
14
15
if (maxHeap.size() < minHeap.size()) {
16
maxHeap.add(minHeap.remove());
17
}
18
}
19
20
public double findMedian() {
21
return minHeap.size() == maxHeap.size() ? 0.5 * (minHeap.peek() + maxHeap.peek()) : maxHeap.peek();
22
}
23
}
24
25
/**
26
* Your MedianFinder object will be instantiated and called as such:
27
* MedianFinder obj = new MedianFinder();
28
* obj.addNum(num);
29
* double param_2 = obj.findMedian();
30
*/
Copied!

3. Time & Space Complexity

Heap: 时间复杂度 addNum: O(logn), findMedian: O(1), 空间复杂度O(n)