295. Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

Examples:

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

For example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


求序列的中位数,序列的元素是动态的加入的,所以中位数也是动态变化的。为了实现动态更新,用两个multiset类型(也可以用优先队列)的集合保存大小两端的子序列,用multiset而不能用set是因为会出现重复的数。要始终保持set1的元素个数大于等于set2的,而且最多只多1个。这样求中位数的时候直接用set1的尾部元素或者用set1的尾部元素加上用set2的头部元素除以2作为答案。如何保持。。看代码实现。这里发现一个有趣的事,想删除set1的尾部元素,本来想用set1.erase(set1.rbegin()),发现不能使用reverse_iterator当参数。。额也不是很有趣。


代码:

class MedianFinder
{
public:
	MedianFinder(){}

	void addNum(int num)
	{
		double n = double(num);
		if(set1.empty()) set1.insert(n);
		else if(set1.size() > set2.size())
		{
			if(n >= *set1.rbegin())
			{
				set2.insert(n);
			}
			else
			{
				set2.insert(*set1.rbegin());
				set1.erase(prev(set1.end()));
				set1.insert(n);
			}
		}
		else
		{
			if(n <= *set2.begin())
			{
				set1.insert(n);
			}
			else
			{
				set1.insert(*set2.begin());
				set2.erase(set2.begin());
				set2.insert(n);
			}
		}
	}

	double findMedian()
	{
		if(set1.size() > set2.size())
		{
			return *set1.rbegin();
		}
		else
		{
			return (*set1.rbegin() + *set2.begin()) / 2;
		}
	}
private:
	multiset<double> set1, set2;

};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值