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.
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
这道题要注意的是:两个无符号数相减的问题
if(pq_left.size() > pq_right.size() + 1 ){
pq_right.push(pq_left.top());
pq_left.pop();
}else if(pq_right.size() > (pq_left.size() + 1)){
pq_left.push(pq_right.top());
pq_right.pop();
}
下面的这种写法不正确,因为两个无符号数相减后还是个正数??
if(pq_left.size() - pq_right.size() > 1 ){
pq_right.push(pq_left.top());
pq_left.pop();
}else if(pq_right.size() - pq_left.size() > 1){
pq_left.push(pq_right.top());
pq_right.pop();
}
class MedianFinder {
public:
// Adds a number into the data structure.
void addNum(int num) {
if(pq_left.empty() || (pq_left.top() > num) ) pq_left.push(num);
else pq_right.push(num);
if(pq_left.size() > pq_right.size() + 1 ){
pq_right.push(pq_left.top());
pq_left.pop();
}else if(pq_right.size() > (pq_left.size() + 1)){
pq_left.push(pq_right.top());
pq_right.pop();
}
}
// Returns the median of current data stream
double findMedian() {
if(pq_left.size() == pq_right.size())
return pq_left.empty() ? 0: ((pq_left.top() + pq_right.top())/2.0);
else
return pq_left.size() > pq_right.size() ? pq_left.top(): pq_right.top();
}
private:
priority_queue<int> pq_left;
priority_queue<int, vector<int>,greater<int>> pq_right;
};
// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();