Numbers keep coming, return the median of numbers at every time a new number added.

维持一个大顶堆,一个小顶堆;大顶堆存有序的前一半数据,小顶堆存有序的后一半数据;大顶堆的堆顶就是每次的中位数。

注意要 维持maxHeap.size()==minHeap.size()+1或者maxHeap.size()==minHeap.size()

参考:​​javascript:void(0)​​

class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The median of numbers
*/
struct mycmp{
bool operator()(const int a,const int b)const{
return a>b;
}
};

vector<int> medianII(vector<int> &nums) {
// write your code here

vector<int> res;
int len=nums.size();
if(len==0){
return res;
}

priority_queue<int> maxHeap;
priority_queue<int,vector<int>,mycmp> minHeap;

maxHeap.push(nums[0]);
res.push_back(nums[0]);

for(int i=1;i<len;i++){
if(nums[i]<=maxHeap.top()){
maxHeap.push(nums[i]);
}else{
minHeap.push(nums[i]);
}

/*维持maxHeap.size()==minHeap.size()+1或者maxHeap.size()==minHeap.size()*/

if(maxHeap.size()>minHeap.size()+1){
int top=maxHeap.top();
maxHeap.pop();
minHeap.push(top);
}

if(maxHeap.size()<minHeap.size()){
int top=minHeap.top();
minHeap.pop();
maxHeap.push(top);
}

res.push_back(maxHeap.top());
}

return res;
}
};