[CareerCup] 18.9 Find and Maintain the Median Value 寻找和维护中位数

18.9 Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.

LeetCode上的原题,请参见我之前的博客Find Median from Data Stream.

解法一:

priority_queue<int> small;
priority_queue<int, vector<int>, greater<int>> large; void addNum(int num) {
small.push(num);
large.push(small.top());
small.pop();
if (small.size() < large.size()) {
small.push(large.top());
large.pop();
}
} double find_median() {
return small.size() > large.size() ? small.top() : 0.5 * (small.top() + large.top());
}

解法二:

priority_queue<int> small, large;

void addNum(int num) {
small.push(num);
large.push(-small.top());
small.pop();
if (small.size() < large.size()) {
small.push(-large.top());
large.pop();
}
} double find_median() {
return small.size() > large.size() ? small.top() : 0.5 * (small.top() - large.top());
}

CareerCup All in One 题目汇总

上一篇:maven项目发布到Tomcat丢失jar包


下一篇:BZOJ3168: [Heoi2013]钙铁锌硒维生素