题目描述:
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.
For example,
[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.
Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
Follow up:
1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {}
void addNum(int num) {
if(max_heap.size()==min_heap.size())
{
min_heap.push(num);
int temp=min_heap.top();
min_heap.pop();
max_heap.push(temp);
}
else
{
min_heap.push(num);
int temp=min_heap.top();
min_heap.pop();
max_heap.push(temp);
temp=max_heap.top();
max_heap.pop();
min_heap.push(temp);
}
}
double findMedian() {
if(min_heap.size()==max_heap.size()) return ((double)min_heap.top()+(double)max_heap.top())/2.0;
else return (double)max_heap.top();
}
private:
priority_queue<int, vector<int>, less<int>> max_heap;
priority_queue<int, vector<int>, greater<int>> min_heap;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
本文介绍了一种数据结构设计,用于实时维护从数据流中读取的所有整数的中位数。通过使用两个堆(最大堆和最小堆),可以在O(log n)时间内插入新元素,并在O(1)时间内找到当前所有元素的中位数。
1万+

被折叠的 条评论
为什么被折叠?



