您的位置:首页 > 其它

295. Find Median from Data Stream

2017-02-15 13:09 337 查看
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;

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  multiset