您的位置:首页 > 其它

leetcode@ [295]Find Median from Data Stream

2015-10-27 12:40 423 查看
https://leetcode.com/problems/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:

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


class MedianFinder {

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

public:

// Adds a number into the data structure.
void addNum(int num) {
if(minHeap.empty() || num <= minHeap.top()){
if(minHeap.size() > maxHeap.size()){
maxHeap.push(minHeap.top());
minHeap.pop();
}
minHeap.push(num);
}
else if(maxHeap.empty() || num > maxHeap.top()){
if(maxHeap.size() > minHeap.size()){
minHeap.push(maxHeap.top());
maxHeap.pop();
}
maxHeap.push(num);
}
else{
if(maxHeap.size() >= minHeap.size()) minHeap.push(num);
else if(minHeap.size() > maxHeap.size()) maxHeap.push(num);
}
}

// Returns the median of current data stream
double findMedian() {
if(minHeap.size() == maxHeap.size()) return (double) (minHeap.top() + maxHeap.top()) / 2.0;
else if(minHeap.size() > maxHeap.size()) return (double) minHeap.top();
else return (double) maxHeap.top();
}
};

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