您的位置:首页 > 其它

leetcode:Find Median from Data Stream

2016-03-21 23:46 405 查看
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:
add(1)
add(2)
findMedian() -> 1.5
add(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

class MedianFinder {

private:
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, less<int>>    maxHeap;

public:

// Adds a number into the data structure.
void addNum(int num) {

if (maxHeap.size() == minHeap.size())
{
if (minHeap.size() != 0 && num > minHeap.top())
{
maxHeap.push(minHeap.top());
minHeap.pop();
minHeap.push(num);
}
else
{
maxHeap.push(num);
}
}
else
{
if (num < maxHeap.top())
{
minHeap.push(maxHeap.top());
maxHeap.pop();
maxHeap.push(num);
}
else
{
minHeap.push(num);
}
}
}

// Returns the median of current data stream
double findMedian() {

if (maxHeap.size() == 0)
return 0;

if (maxHeap.size() == minHeap.size())
return ((double)minHeap.top()+(double)maxHeap.top())/2;
else
return (double)maxHeap.top();
}
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: