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.
Example:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
思路:
这道题我们主要参考了LeetCode给出的官方解答:here,这里贴出使用两个优先级队列来处理问题的方法,非常有趣:
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
low.push(num);
high.push(low.top());
low.pop();
if (low.size() < high.size()) {
low.push(high.top());
high.pop();
}
}
double findMedian() {
return low.size() == high.size() ? double(low.top() + high.top()) * 0.5 : low.top();
}
private:
priority_queue<int> low;
priority_queue<int, vector<int>, greater<int>> high;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/