[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 题目汇总

 

posted @ 2016-05-09 23:07  Grandyang  阅读(625)  评论(0编辑  收藏  举报
Fork me on GitHub