1. 程式人生 > >[CareerCup] 18.9 Find and Maintain the Median Value 尋找和維護中位數

[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.

解法一:

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()); }