-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path295.find-median-from-data-stream.cpp
More file actions
42 lines (36 loc) · 1.05 KB
/
295.find-median-from-data-stream.cpp
File metadata and controls
42 lines (36 loc) · 1.05 KB
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
35
36
37
38
39
40
41
42
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> left;
priority_queue<int, vector<int>, greater<int>> right;
int counter = 0;
MedianFinder() {
}
void addNum(int num) {
if(left.size() == 0 || num < left.top())
left.push(num);
else
right.push(num);
if((int)left.size() - (int)right.size() > 1){
right.push(left.top());
left.pop();
}else if((int)right.size() - (int)left.size() > 1){
left.push(right.top());
right.pop();
}
}
double findMedian() {
if(left.size() == right.size())
return (left.top() + right.top())/2.0;
else if((int)left.size() >right.size())
return left.top();
else
return right.top();
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/