-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-median-from-data-stream.cpp
55 lines (47 loc) · 1.31 KB
/
find-median-from-data-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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(max_pq.size() == 0 && min_pq.size() == 0){
max_pq.push(num);
}
else if( num > max_pq.top()){
min_pq.push(num);
}
else{
max_pq.push(num);
}
if(max_pq.size() - min_pq.size() == 2){
min_pq.push(max_pq.top());
max_pq.pop();
}
if(min_pq.size() - max_pq.size() == 2){
max_pq.push(min_pq.top());
min_pq.pop();
}
}
double findMedian() {
double ans;
if(min_pq.size() == max_pq.size()){
ans = (double)(min_pq.top() + max_pq.top()) / 2.0;
}
if(min_pq.size() > max_pq.size()){
ans = (double)min_pq.top();
}
if(min_pq.size() < max_pq.size()){
ans = (double)max_pq.top();
}
return ans;
}
private:
priority_queue<int, vector<int>, less<int>> max_pq;
priority_queue<int, vector<int>, greater<int>> min_pq;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/