295. Find Median from Data Stream

Description

image-20210827232342741

image-20210827232353015

Solution

Because we are handling a stream problem, if we need resort the array each time it is a costy solution. So if we could have a self-balance binary search tree, we could use the top of the tree as the answer, but just writing a AVL or RBT is not very troublesome. A better solution is to use two priority queue, one is min heap and other is max heap.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int,vector<int>, greater<>> heapMin;
priority_queue<int,vector<int>, less<>> heapMax;
MedianFinder() {
}

void addNum(int num) {
if(heapMin.empty() || heapMin.top() <= num){
heapMin.push(num);
if(heapMin.size() > heapMax.size() + 1){
heapMax.push(heapMin.top());
heapMin.pop();
}
}else{
heapMax.push(num);
if(heapMax.size() >= heapMin.size() + 1){
heapMin.push(heapMax.top());
heapMax.pop();
}
}
}

double findMedian() {
if(heapMax.size() == heapMin.size())
return 1.0 * (heapMax.top() + heapMin.top()) /2;
return heapMin.top();
}
};

image-20210827233938645