-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind mean from Data stream
59 lines (56 loc) · 1.53 KB
/
Find mean from Data stream
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
56
57
58
59
class MedianFinder {
public:
MedianFinder() {
}
priority_queue<int,vector<int> > pqmax;
priority_queue<int, vector<int>, greater<int> > pqmin;
void addNum(int num) {
if(pqmin.size()==pqmax.size()){
if(pqmax.size()==0){
pqmax.push(num);
return;
}
if(num<pqmax.top()){
pqmax.push(num);
}else{
pqmin.push(num);
}
}else{
if(pqmin.size()<pqmax.size()){
if(num>=pqmax.top()){
pqmin.push(num);
}else{
int temp=pqmax.top();
pqmax.pop();
pqmin.push(temp);
pqmax.push(num);
}
}else{
if(num<=pqmin.top()){
pqmax.push(num);
}else{
int temp=pqmin.top();
pqmin.pop();
pqmax.push(temp);
pqmin.push(num);
}
}
}
}
double findMedian() {
if(pqmin.size()==pqmax.size()){
return ((pqmin.top()+pqmax.top())/2.0);
}
else if(pqmin.size()>pqmax.size()){
return pqmin.top();
}else{
return pqmax.top();
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/