// Median.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<queue>
using namespace::std;
class Median
{
private:
priority_queue<int,vector<int>,less<int>> maxheap; //12345
priority_queue<int,vector<int>,greater<int>> minheap; //98765
public:
void Insert(int v);
int getmedian();
}
void Median::Insert(int v)
{
if(maxheap.size()==minheap.size())
{
if((minheap.top()!=NULL)&&(v>minheap.top()))
{
int tmp=minheap.top();
minheap.pop();
maxheap.push(tmp);
minheap.push(v);
}else
{
maxheap.push(v);
}
}
else
{
if(maxheap.top()!=NULL&&v<maxheap.top())
{
int tmp=maxheap.top();
maxheap.pop();
minheap.push(tmp);
maxheap.push(v);
}
else
{
minheap.push(v);
}
}
}
int Median::getmedian()
{
if(maxheap.empty())
return 0;
if(maxheap.size()==minheap.size())
{
return (maxheap.top()+minheap.top())/2;
}
else
{
return maxheap.top();
}
}
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<queue>
using namespace::std;
class Median
{
private:
priority_queue<int,vector<int>,less<int>> maxheap; //12345
priority_queue<int,vector<int>,greater<int>> minheap; //98765
public:
void Insert(int v);
int getmedian();
}
void Median::Insert(int v)
{
if(maxheap.size()==minheap.size())
{
if((minheap.top()!=NULL)&&(v>minheap.top()))
{
int tmp=minheap.top();
minheap.pop();
maxheap.push(tmp);
minheap.push(v);
}else
{
maxheap.push(v);
}
}
else
{
if(maxheap.top()!=NULL&&v<maxheap.top())
{
int tmp=maxheap.top();
maxheap.pop();
minheap.push(tmp);
maxheap.push(v);
}
else
{
minheap.push(v);
}
}
}
int Median::getmedian()
{
if(maxheap.empty())
return 0;
if(maxheap.size()==minheap.size())
{
return (maxheap.top()+minheap.top())/2;
}
else
{
return maxheap.top();
}
}