题解 | #数据流中的中位数#
数据流中的中位数
http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
class Solution {
public:
priority_queue<int> qmin;
priority_queue<int, vector<int>, greater<int>> qmax;
void Insert(int num) {
if (qmin.empty() || num <= qmin.top()) {
qmin.push(num);
if (qmin.size() - 1 > qmax.size()) {
qmax.push(qmin.top());
qmin.pop();
}
} else {
qmax.push(num);
if (qmax.size() > qmin.size()) {
qmin.push(qmax.top());
qmax.pop();
}
}
}
double GetMedian() {
if (qmin.size() == qmax.size()) return (qmin.top() + qmax.top()) / 2.0;
return qmin.top();
}
};