题目:数据流的中位数
- 题目描述:
中位数是排序后列表的中间值。如果列表的大小是偶数,则没有中间值,此时中位数是中间两个数的平均值。
示例:
[2,3,4] , 中位数是 3
[2,3], 中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
- void addNum(int num) - 从数据流中增加一个整数到数据结构中。
double findMedian() -返回目前所有元素的中位数。
例如:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
#include <queue>
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(big_queue.empty()){
big_queue.push(num);
return;
}
if(big_queue.size()==small_queue.size()){
if(num<big_queue.top()){
big_queue.push(num);
}
else{
small_queue.push(num);
}
}
else if(big_queue.size()>small_queue.size()){
if(num>big_queue.top()){
small_queue.push(num);
}
else{
small_queue.push(big_queue.top());
big_queue.pop();
big_queue.push(num);
}
}
else if(big_queue.size()<small_queue.size()){
if(num<small_queue.top()){
big_queue.push(num);
}
else{
big_queue.push(small_queue.top());
small_queue.pop();
small_queue.push(num);
}
}
}
double findMedian() {
if(big_queue.size()==small_queue.size()){
return (big_queue.top()+small_queue.top())/2;
}
else if(big_queue.size()>small_queue.size()){
return big_queue.top();
}
return small_queue.top();
}
private:
priority_queue<double,vector<double>,greater<double> > small_queue;
priority_queue<double,vector<double>,less<double> > big_queue;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/