Problem: 295. 数据流的中位数
题目描述
思路
1.定义一个大顶堆和小顶堆;
2.当添加的数据小于大顶堆的堆顶元素或者大顶堆为空时,将元素添加到大顶堆;当元素大于大顶堆堆顶元素时添加到小顶堆;同时维护大小顶堆,当大顶堆的元素个数小于小顶堆时,将小顶堆多出大顶堆个数的堆顶元素拿出添加到大顶堆;当小顶堆元素小于大顶堆元素个数减1时将大顶堆多出的堆顶元素添加到小顶堆;
3.当大小顶堆的元素个数一样时,取各自的堆顶元素相加除以2;否则取出大顶堆的堆顶元素;
复杂度
时间复杂度:
O ( l o g n ) O(logn) O(logn);其中 n n n为数据数据流的数据个数
空间复杂度:
O ( n ) O(n) O(n)
Code
class MedianFinder {
private:
// Maintain a max heap and a min heap
priority_queue<int, vector<int>, less<int>> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
public:
// Constructor
MedianFinder() {
}
// Insert data into the data stream
void addNum(int num) {
if (maxHeap.empty() || num <= maxHeap.top()) {
maxHeap.push(num);
} else {
minHeap.push(num);
}
// Maintain the number relationship between two heaps
// 1. The number of elements in the max heap is not less than that in the min heap
// 2. The number of min heap elements can be less than the number of max heap elements minus 1
while (maxHeap.size() < minHeap.size()) {
int temp = minHeap.top();
minHeap.pop();
maxHeap.push(temp);
}
while (minHeap.size() < maxHeap.size() - 1) {
int temp = maxHeap.top();
maxHeap.pop();
minHeap.push(temp);
}
}
// Find the median
double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (minHeap.top() + maxHeap.top()) / 2.0;
} else {
return maxHeap.top();
}
}
};