-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathmedian_stream.cpp
34 lines (30 loc) · 934 Bytes
/
median_stream.cpp
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
31
32
33
34
/*
Problem Link: https://leetcode.com/problems/find-median-from-data-stream/
*/
class MedianFinder {
public:
priority_queue<int> maxHeap; // max of the left part
priority_queue<int, vector<int>, greater<int>> minHeap; // min of right part
void addNum(int num) {
// left side of the array
if(maxHeap.empty() || num <= maxHeap.top())
maxHeap.push(num);
else
minHeap.push(num);
// balance the 2 heaps
if(maxHeap.size() < minHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
else if(maxHeap.size() - minHeap.size() >= 2) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
double findMedian() {
if(maxHeap.size() == minHeap.size())
return (maxHeap.top() + minHeap.top()) / 2.0;
else
return maxHeap.top();
}
};