问题:有一个每刻都在往外吐数据的机器,要求随时打印其中位数,时间复杂度为O(N)。
思路:运用堆的性质,准备一个大根堆,一个小根堆,每次吐的数据都进入小根堆中,当发现小根堆的size比大根堆多2个时,此时小根堆头节点出堆进入大根堆中,这样两个堆的size差距最多为1,中位数必然是两个堆的头节点取得。当然,如果总的数据个数为偶数,需要对两个堆头节点取平均值。
对于stl中比较器不了解的可以查阅https://blog.csdn.net/qq_42673507/article/details/85557902
#include <iostream>
#include <queue>
using namespace std;
//仿函数作为比较器
struct cmp1 {
bool operator()(int a,int b)const {
if (a > b) {
return true;
}
else {
return false;
}
}
};
struct cmp2 {
bool operator()(int a, int b)const {
if (a < b) {
return true;
}
else {
return false;
}
}
};
int main()
{
priority_queue<int, vector<int>,cmp2>big_heap;
priority_queue<int, vector<int>,cmp1>small_heap;
int a,count = 0;
while (cin >> a) {
count++;
small_heap.push(a);
if (small_heap.size()- big_heap.size()>1) {
big_heap.push(small_heap.top());
small_heap.pop();
}
if (count % 2 == 0) {
cout << "中位数为:" << (small_heap.top()+ big_heap.top()) / 2 << endl;
}
else {
if (count == 1) {
cout << "中位数为:" << small_heap.top() << endl;
}
else {
cout << "中位数为:" << (small_heap.top() > big_heap.top() ? small_heap.top() : big_heap.top()) << endl;
}
}
}
return 0;
}