295. Find Median from 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.
Solution
C++
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> Min; //big heap
priority_queue<int,vector<int>,greater<int> > Max; //small heap
MedianFinder() {
}
void addNum(int num) {
if(Min.size() == Max.size()) {
if(Max.size() == 0 || num <= Max.top()) Min.push(num);
else {
Min.push(Max.top());
Max.pop();
Max.push(num);
}
}
else {
if(num >= Min.top()) Max.push(num);
else {
Max.push(Min.top());
Min.pop();
Min.push(num);
}
}
}
double findMedian() {
if(Min.size() == Max.size()) {
return (double)(Min.top() + Max.top()) / 2;
}
return Min.top();
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
Explanation
大顶堆、小顶堆