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 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.
For example:
add(1) add(2) findMedian() -> 1.5 add(3) findMedian() -> 2
The main point is to use a maxHeap and minHeap. maxHeap stores the first half part of input numbers. minHeap stores the second half part of input numbers.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class MedianFinder {
private:
priority_queue< int, vector<int>, greater<int> > minHeap;
priority_queue< int, vector<int>, less<int> > maxHeap;
public:
void addNum(int num) {
minHeap.push(num);
if(minHeap.size() - maxHeap.size() > 1) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
if(maxHeap.size() > minHeap.size()) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
double findMedian() {
if(minHeap.size() == maxHeap.size()) return (minHeap.top() + maxHeap.top()) / 2.0;
else return (double) minHeap.top();
}
};
int main(void) {
MedianFinder finder;
finder.addNum(1);
finder.addNum(2);
finder.addNum(3);
cout << finder.findMedian() << endl;
}