当前位置:网站首页>从数据流中快速查找中位数
从数据流中快速查找中位数
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;
}
};
边栏推荐
猜你喜欢

实战演练 | 在 MySQL 中计算每日平均日期或时间间隔

一个近乎完美的 Unity 全平台热更方案

A new generation of free open source terminal tool, so cool
![idea2021+Activiti [the most complete note one (basic use)]](/img/60/55cccf257523bed2c8829361cea97c.png)
idea2021+Activiti [the most complete note one (basic use)]

Quick Start Tutorial for flyway

EViews 12.0软件安装包下载及安装教程

Day113. Shangyitong: WeChat login QR code, login callback interface

Re16:读论文 ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation

Meikle Studio-Look at Hongmeng Device Development Practical Notes 7-Network Application Development

Security Thought Project Summary
随机推荐
nacos实战项目中的配置
STM32CubeMX configuration to generate FreeRTOS project
多线程--线程和线程池的用法
线上靶机prompt.ml
一个近乎完美的 Unity 全平台热更方案
Determine whether a tree is a complete binary tree - video explanation!!!
Re17: Read the paper Challenges for Information Extraction from Dialogue in Criminal Law
论文阅读:SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers
(文字)无框按钮设置
Re15:读论文 LEVEN: A Large-Scale Chinese Legal Event Detection Dataset
shell script
Re19:读论文 Paragraph-level Rationale Extraction through Regularization: A case study on European Court
方法的参数传递
New in GNOME: Warn users when Secure Boot is disabled
JVM内存布局、类加载机制及垃圾回收机制详解
The thread pool method opens the thread -- the difference between submit() and execute()
kubernetes的一些命令
The creation of a large root heap (video explanation)
BERT pre-training model series summary
idea2021+Activiti [the most complete note one (basic use)]