初学见解
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class toGetMedian{
private:
vector<int> maxheap;
vector<int> minheap;
public:
void Insert(int num)
{
int size = maxheap.size() + minheap.size();
if(size&1){
int tmp = num;
if((!maxheap.empty())&&(num < maxheap[0])){
tmp = maxheap[0];
maxheap[0] = num;
make_heap(maxheap.begin(),maxheap.end());
}
minheap.push_back(tmp);
push_heap(minheap.begin(),minheap.end(),greater<int>());
}
else{
int tmp = num;
if((!minheap.empty())&&(num > minheap[0])){
tmp = minheap[0];
minheap[0] = num;
make_heap(minheap.begin(),minheap.end(),greater<int>());
}
maxheap.push_back(tmp);
push_heap(maxheap.begin(),maxheap.end());
}
}
double GetMedian()
{
int size = maxheap.size() + minheap.size();
double median;
if(size & 1){
median = maxheap[0];
}
else{
median = (maxheap[0] + minheap[0])/2.;
}
return median;
}
};
int main()
{
toGetMedian test;
test.Insert(1);
test.Insert(7);
test.Insert(3);
test.Insert(8);
test.Insert(17);
test.Insert(62);
test.Insert(2);
cout << test.GetMedian() << endl;
return 0;
}
大佬链接:https://blog.csdn.net/m0_37950361/article/details/80537646