1. Topic
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.
Source: prove safety offer
links: https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&tqId=11216&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
2. My problem solution
- Top of the heap using large
left
save small half figures, the big top heapright
hold larger half figures; - Determining which of a stack to be inserted is inserted;
- Ensure that the two heap size difference is not more than
1
, if not the same size, so big top priority heap left larger;
class Solution {
priority_queue<int,vector<int>,less<int> > left;//大顶堆
priority_queue<int,vector<int>,greater<int> >right;//小顶堆
public:
void Insert(int num)
{
if(left.empty() || num<left.top())left.push(num);
else right.push(num);
if(left.size()>right.size()+1){
right.push(left.top());
left.pop();
}
if(right.size()>left.size()){
left.push(right.top());
right.pop();
}
}
double GetMedian()
{
if(left.empty() && right.empty())return 0;
if(left.size()==right.size()+1)return left.top();
return 0.5 * (left.top()+right.top());
}
};
3. someone else's problem solution
4. Summary and Reflection
(1) C++
in priority_queue<int,vector< int >,less< int > >
the default heap big top;
priority_queue<int,vector< int >,greater< int > >
small pile top;