随机提取中位数

题目:Numbers are randomly generated and stored into an (expanding) array. How would you keep track of the median?

思路分析:使用两个堆,一个最大堆(存储小于中位数的一半的元素),一个最小堆(存储大于中位数的一半的元素),只要维护好这两个堆,根据堆顶元素就能得到中位数。我们的程序保证左右两个堆的元素个数差不能超过1,设最大堆堆顶元素为x1,最小堆堆顶元素为x2,则若插入元素x>x2,则将该元素插入最小堆中,若最小堆元素个数-最大堆元素个数>1,将最小堆堆顶元素弹出到最大堆中去;若x1<=x<=x2,插入任意一个堆中;若x<x1,同x>x2的情况。


#include<iostream>
#include<queue>
using namespace std;

//最后的> >中间要有一个空格,避免被编译器理解为移位操作

//大顶堆 
priority_queue<int,vector<int>,less<int> > maxheap;
//小顶堆 
priority_queue<int,vector<int>, greater<int> > minheap;

void insert(int x){
	//insert into any heap
	if(maxheap.size()==0&&minheap.size()==0)
		maxheap.push(x);
	//rebalance it 
	else if(maxheap.size()==0&&minheap.size()==1){
		if(x>minheap.top()){
			maxheap.push(minheap.top());
			minheap.pop();minheap.push(x);
		}else{
			maxheap.push(x);
		}
	}
	//rebalance it
	else if(maxheap.size()==1&&minheap.size()==0){
		if(x<maxheap.top()){
			minheap.push(maxheap.top());
			maxheap.pop();maxheap.push(x);
		}else{
			minheap.push(x);
		}
	}
	//insert
	else{
		if(x>minheap.top()){
			minheap.push(x);
			if(minheap.size()-maxheap.size()>1){
				int tmp=minheap.top();minheap.pop();
				maxheap.push(tmp);
			}
		}else if(x<maxheap.top()){
			maxheap.push(x);
			if(maxheap.size()-minheap.size()>1){
				int tmp=maxheap.top();maxheap.pop();
				maxheap.push(tmp);
			}
		}else{
			//插入任意一个 
			if(maxheap.size()==minheap.size()){
				maxheap.push(x);
			}else if(maxheap.size()-minheap.size()==1){
				minheap.push(x);
			}else{
				maxheap.push(x);
			}
		}
	}
}

int getMid(){
	if(minheap.size()-maxheap.size()==1)
	    return minheap.top();
	else if(maxheap.size()-minheap.size()==1)
		return maxheap.top();
	else
		return min(maxheap.top(),minheap.top());//这一句很重要,可能出现最大堆是:5 5 最小堆是:6 6 这种情况,我们必须取两者中的最小值。
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值