0
点赞
收藏
分享

微信扫一扫

算法 中位数 之 堆处理

目标践行者 2022-03-27 阅读 38

7

1 3 5 7 9 11 6

1

3

5

6

#pragma warning(disable : 4996)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

class GetMedian {
private:
    priority_queue<int, vector<int>, greater<int>> small_heap;
    priority_queue<int, vector<int>, less<int>> big_heap;
public:
    GetMedian() {};
    void push(int num);
    double getMedia();
    void print();
};
void GetMedian::print()
{
    stack<int> s;
    double media = getMedia();
    if (small_heap.top() == media )
        s.push(media);

    while (!big_heap.empty())
    {
        s.push(big_heap.top());
        big_heap.pop();
    }
    while (!s.empty())
    {
        cout << s.top() << endl;
        s.pop();
    }
}
void GetMedian::push(int num) {
    if (small_heap.empty()) {
        small_heap.push(num);
        return;
    }

    if (big_heap.size() == small_heap.size()) {
        if (num < big_heap.top()) {
            big_heap.push(num);
        }
        else {
            small_heap.push(num);
        }
    }
    else if (big_heap.size() > small_heap.size()) {
        if (num < big_heap.top()) {
            small_heap.push(big_heap.top());
            big_heap.pop();
            big_heap.push(num);
        }
        else {
            small_heap.push(num);
        }
    }
    else {
        if (num > small_heap.top()) {
            big_heap.push(small_heap.top());
            small_heap.pop();
            small_heap.push(num);
        }
        else {
            big_heap.push(num);
        }
    }
}
 
double GetMedian::getMedia() {
    double median;

    if (small_heap.size() == big_heap.size()) {
        median = ((double)small_heap.top() + (double)big_heap.top()) / 2;
    }
    else if (small_heap.size() < big_heap.size()) {
        median = (double)big_heap.top();
    }
    else {
        median = (double)small_heap.top();
    }

    return median;
} 

int main() {
    GetMedian m;
    int tmp;
    int n;

    
    cin >> n;
    
    for (int i = 0; i < n; ++i) {
        cin >> tmp;
        m.push(tmp);
    }    
    m.print();
    return 0;
}
举报

相关推荐

0 条评论