Title Description
How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.
Thinking
By the data stream insert function in ascending order
by GetMedian (corresponding to the output) the median
Code
class Solution {
public:
vector<int> res;
void Insert(int num){
int i = 0;
if(res.size()==0)
{
res.push_back(num);
return;
}
for(i=0;i<res.size();i++)
{
if(num < res[i])
{
res.insert(res.begin()+i,num);
return;
}
}
res.push_back(num);
return;
}
double GetMedian()
{
int size = res.size();
if(size%2 == 0)
{
return (res[size/2-1] + res[size/2])/2.0;
}
else
return res[(size-1)/2];
}
};