剑指OFFER41
在C++中使用priority_queue类型变量
//升序队列:先弹出的值是最小值,保留最大值在队列中
priority_queue <int,vector,greater > q;
//降序队列:先弹出的值是最大值,保留最小值在队列中,默认为less
priority_queue <int,vector,less >q;
small_heap存储数值较小的数,big_heap存储数值较大的数
addNum函数:
当small_heap为空,优先存储到small_heap
当两变量尺寸大小一样,则将num与small_heap.top()比较,大的话存储到big_heap中,否则存储到small_heap中
当small_heap尺寸较大时,则将num与small_heap.top()比较,大的话存储到big_heap中;否则先将small_heap.top()存储到big_heap中并弹出small_heap.top(),之后再将num存储到small_heap中
当big_heap尺寸较大时,则将num与big_heap.top()比较,小的话直接存储到small_heap中;否则先将big_heap.top()存储到small_heap中,再弹出big_heap.top(),之后再将num存储到big_heap中
findMedian函数:
如果small_heap和big_heap尺寸大小一样,则返回二者堆顶的平均值
否则返回尺寸较大的变量的堆顶值
class MedianFinder {
public:
priority_queue<int,vector<int>,less<int>> small_heap;
priority_queue<int,vector<int>,greater<int>> big_heap;
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(small_heap.empty()){
small_heap.push(num);
return;
}
if(small_heap.size()==big_heap.size()){
if(num>=small_heap.top()){
big_heap.push(num);
}
else{
small_heap.push(num);
}
}
else if(small_heap.size() > big_heap.size()){
if(num >= small_heap.top()){
big_heap.push(num);
}
else{
big_heap.push(small_heap.top());
small_heap.pop();
small_heap.push(num);
}
}
else if(small_heap.size() < big_heap.size()){
if(num <= big_heap.top()){
small_heap.push(num);
}
else{
small_heap.push(big_heap.top());
big_heap.pop();
big_heap.push(num);
}
}
}
double findMedian() {
if(small_heap.size() == big_heap.size()){
return 0.5*(small_heap.top()+big_heap.top());
}
return big_heap.size()>small_heap.size()?big_heap.top():small_heap.top();
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/