[CareerCup] 18.9 Find and Maintain the Median Value 尋找和維護中位數

Grandyang發表於2016-05-09

 

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 題目彙總

 

相關文章