题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
解法1:暴力解
每进来一个都对它做排序,然后再求中位数
解法2:使用大小堆
这里使用STL中的优先队列,它底层是用堆实现的
ps:当用于自定义类型时,只需要重载运算符即可
测试结果及代码
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
void printArray(int a[], int N) {
for (int i = 0; i < N; ++i) {
cout << a[i] << " ";
}
// cout << endl;
}
void compare(vector<int> a) {
vector<int> t;
for (int i = 0; i < a.size(); ++i) {
t.push_back(a[i]);
sort(t.begin(), t.end());
cout << "\n当前序列:";
for (const auto &j : t) {
cout << j << " ";
}
double res = 0;
size_t sz = t.size();
cout << ",size为:" << sz;
if<