当前位置:网站首页>从数据流中快速查找中位数
从数据流中快速查找中位数
2022-07-30 09:50:00 【Currybeefer】

这题的思路就是维护两个堆,一个大根堆一个小根堆,将数据加入到这两个堆中,这样从两个堆的堆顶就可以获取整个数据的中位数。
C++中的priority_queue 默认是以大根堆存储的,也就是说,堆顶是堆中最大的元素。如果要定义小根堆,那么就得自己写一个仿函数。具体看代码注释
class MedianFinder
{
class cmp
{
public:
bool operator()(double a,double b)
{
return a>b;//返回true时,优先级会更低,也就是a的优先级会低于b,a会往堆底调整
}
};
priority_queue<double,vector<double>,cmp> Small;//构建小顶堆
priority_queue<double,vector<double>> Large;//构建大顶堆
public:
MedianFinder()
{
}
void addNum(int num)
{
if(Large.size()==0 && Small.size()==0)//第一个加入的元素默认先放在Large
{
Large.push(num);
return;
}
if(num<=Large.top())//如果num小于Large的堆顶,那么num就放入Large堆中
{
Large.push(num);
cout<< num<<"push to large"<<endl;
}
else//若num大于Large堆顶,也就是比Large最大的大,那么放入Small中
{
Small.push(num);
cout<< num<<"push to small"<<endl;
}
//如果两个堆的数量之差为2,那么需要重新调整一下大小,把大的那个堆顶元素放在小的那个堆上
//为什么差为2的时候调整?因为这样就可以保证调整完后,两个堆数量一致。(3:1)->(2:2)这样的
if(Large.size()-Small.size()==2)
{
int temp=Large.top();
Large.pop();
Small.push(temp);
return;
}
if(Small.size()-Large.size()==2)
{
int temp=Small.top();
Small.pop();
Large.push(temp);
return;
}
}
double findMedian()
{
if(Small.size()>Large.size())
return Small.top();
else if(Small.size()<Large.size())
return Large.top();
return (Small.top()+Large.top())/2;
}
};
边栏推荐
- Beijing suddenly announced big news in the Metaverse
- what is this method called
- Flask's routing (app.route) detailed
- 方法的参数传递
- A near-perfect Unity full-platform hot update solution
- 105. 从前序与中序遍历序列构造二叉树(视频讲解!!)
- Meikle Studio - see the actual combat notes of Hongmeng equipment development five - drive subsystem development
- 第2章 常用安全工具
- Multithreading--the usage of threads and thread pools
- Soft Exam System Architect Concise Tutorial | Case Analysis | Requirement Analysis
猜你喜欢

在机器人行业的专业人士眼里,机器人行业目前的情况如何?

Re21: Read the paper MSJudge Legal Judgment Prediction with Multi-Stage Case Representation Learning in the Real

flowable工作流所有业务概念

Flink_CDC construction and simple use

多线程--线程和线程池的用法

阿里云OSS对象存储

Do you really understand the 5 basic data structures of Redis?

Multithreading--the usage of threads and thread pools

Flask之路由(app.route)详解

BERT pre-training model series summary
随机推荐
北京突然宣布,元宇宙重大消息
[Deep Learning] (Problem Record)
- Linear Regression - Small Batch Stochastic Gradient Descent 时刻铭记:总有一天你将破蛹而出
2022年顶会accepted papers list
Re16: Read the paper ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation
【HMS core】【FAQ】HMS Toolkit典型问题合集1
Matplotlib--绘图标记
PyQt5 - draw text on window
(BUG record) No module named PIL
606. Create a string from a binary tree (video explanation!!!)
Basemap and Seaborn
GNOME 新功能:安全启动被禁用时警告用户
If someone asks you about distributed transactions again, throw this to him
Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解
学习笔记10--局部轨迹生成主要方法
元宇宙改变人类工作模式的四种方式
Flask's routing (app.route) detailed
The method of parameter passing
In 2022, the top will be accepted cca shut the list
分页 paging