# 剑指offer 数据流中的中位数

## 题目描述

class Solution {
priority_queue<int, vector<int>, less<int> > p;
priority_queue<int, vector<int>, greater<int> > q;
public:
void Insert(int num)
{
if(p.empty() || num <= p.top()) p.push(num);
else q.push(num);
if(p.size() == q.size() + 2) q.push(p.top()), p.pop();
if(p.size() + 1 == q.size()) p.push(q.top()), q.pop();
}

double GetMedian()
{
return p.size() == q.size() ? (p.top() + q.top()) / 2.0 : p.top();
}

};

class Solution {
public:
void Insert(int num)
{
count+=1;
// 元素个数是偶数时,将小顶堆堆顶放入大顶堆
if(count%2==0){
big_heap.push(num);
small_heap.push(big_heap.top());
big_heap.pop();
}
else{
small_heap.push(num);
big_heap.push(small_heap.top());
small_heap.pop();
}
}

double GetMedian()
{
if(count&0x1){
return big_heap.top();
}
else{
return double((small_heap.top()+big_heap.top())/2.0);
}
}
private:
int count=0;
priority_queue<int, vector<int>, less<int>> big_heap;        // 左边一个大顶堆
priority_queue<int, vector<int>, greater<int>> small_heap;   // 右边一个小顶堆
// 大顶堆所有元素均小于等于小顶堆的所有元素.
};