# 【编程题】数据流中的中位数

## 我的代码（2018年9月2日）

class Solution {
private:
vector<int> minheap, maxheap;
public:
void Insert(int num)
{
if(maxheap.size() == 0) {
maxheap.push_back(num);
return;
}
if(maxheap.size() - minheap.size() == 1) {
minheap.push_back(num);
push_heap(minheap.begin(), minheap.end(), greater<int>());
}
else {
maxheap.push_back(num);
push_heap(maxheap.begin(), maxheap.end(), less<int>());
}

if(minheap[0] < maxheap[0]) {
pop_heap(minheap.begin(), minheap.end(), greater<int>());
pop_heap(maxheap.begin(), maxheap.end(), less<int>());
swap(minheap.back(), maxheap.back());
push_heap(minheap.begin(), minheap.end(), greater<int>());
push_heap(maxheap.begin(), maxheap.end(), less<int>());
}
}

double GetMedian()
{
double res = 0.0;
if(minheap.size() == maxheap.size()) {
res = (double)(minheap[0] + maxheap[0]) / 2;
}
else {
res = maxheap[0];
}
return res;
}

};

### 我的代码

class Solution {
private:
vector<int> min, max;
public:
void Insert(int num)
{
if(max.size() == 0) {
max.push_back(num);
return ;
}

if(num > max[0]) {
min.push_back(num);
push_heap(min.begin(), min.end(), greater<int>());
}
else {
max.push_back(num);
push_heap(max.begin(), max.end(), less<int>());
}

if(min.size() > max.size()) {
int tmp = min[0];
pop_heap(min.begin(), min.end(), greater<int>());
min.pop_back();
max.push_back(tmp);
push_heap(max.begin(), max.end(), less<int>());
}
else if(max.size() - min.size() > 1) {
int tmp = max[0];
pop_heap(max.begin(), max.end(), less<int>());
max.pop_back();
min.push_back(tmp);
push_heap(min.begin(), min.end(), greater<int>());
}

}

double GetMedian()
{
int len = min.size() + max.size();
if(len == 0) return 0.0;
else if(len == 1) return (double)(max[0]);
else if(len % 2 == 0) return (double)(min[0] + max[0])/2.0;
else return (double)(max[0]);
}

};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120