随机生成数字,并记录中位数

本文介绍了一种使用最大堆和最小堆实现在线中位数计算的方法,通过插入元素到堆中,保持两个堆平衡,从而高效地计算中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Median.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include<iostream>
#include<string>
#include<queue>
using namespace::std;


class Median
{
private:
priority_queue<int,vector<int>,less<int>> maxheap;  //12345
priority_queue<int,vector<int>,greater<int>> minheap; //98765
public:
void Insert(int v);
int getmedian();
}


void Median::Insert(int v)
{
if(maxheap.size()==minheap.size())
{
if((minheap.top()!=NULL)&&(v>minheap.top()))
{
int tmp=minheap.top();
minheap.pop();
maxheap.push(tmp);
minheap.push(v);
}else
{
maxheap.push(v);
}
}
else 
{
if(maxheap.top()!=NULL&&v<maxheap.top())
{
int tmp=maxheap.top();
maxheap.pop();
minheap.push(tmp);
maxheap.push(v);
}
else
{
minheap.push(v);
}
}
}


int Median::getmedian()
{
if(maxheap.empty())
return 0;
if(maxheap.size()==minheap.size())
{
return (maxheap.top()+minheap.top())/2;
}
else
{
return maxheap.top();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值