数据流中获取随时获取中位数(堆结构的应用)

问题:有一个每刻都在往外吐数据的机器,要求随时打印其中位数,时间复杂度为O(N)。

思路:运用堆的性质,准备一个大根堆,一个小根堆,每次吐的数据都进入小根堆中,当发现小根堆的size比大根堆多2个时,此时小根堆头节点出堆进入大根堆中,这样两个堆的size差距最多为1,中位数必然是两个堆的头节点取得。当然,如果总的数据个数为偶数,需要对两个堆头节点取平均值。
对于stl中比较器不了解的可以查阅https://blog.csdn.net/qq_42673507/article/details/85557902

#include <iostream>
#include <queue>
using namespace std;
//仿函数作为比较器
struct cmp1 {
	bool operator()(int a,int b)const {
		if (a > b) {
			return true;
		}
		else {
			return false;
		}
	}
};
struct cmp2 {
	bool operator()(int a, int b)const {
		if (a < b) {
			return true;
		}
		else {
			return false;
		}
	}
};
int main()
{
	priority_queue<int, vector<int>,cmp2>big_heap;
	priority_queue<int, vector<int>,cmp1>small_heap;
	int a,count = 0;
	while (cin >> a) {
		count++;
		small_heap.push(a);
		if (small_heap.size()- big_heap.size()>1) {
			big_heap.push(small_heap.top());
			small_heap.pop();
		}
		if (count % 2 == 0) {
			cout << "中位数为:" << (small_heap.top()+ big_heap.top()) / 2 << endl;
		}
		else {
			if (count == 1) {
				cout << "中位数为:" << small_heap.top() << endl;
			}
			else {
				cout << "中位数为:" << (small_heap.top() > big_heap.top() ? small_heap.top() : big_heap.top()) << endl;
			}
		}
	}
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值