-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path295. Find Median from Data Stream.cpp
73 lines (65 loc) · 1.51 KB
/
295. 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class MedianFinder {
public:
priority_queue<int>l;
priority_queue<int,vector<int>,greater<int>>r;
double med;
MedianFinder() {
}
void addNum(int num) {
if(l.size()==0 && r.size()==0)
{
med=num;
l.push(med);
}
else if(l.size()>r.size())
{
if(num<med)
{
r.push(l.top());
l.pop();
l.push(num);
}
else
{
r.push(num);
}
med=(l.top()+r.top())/2.0;
}
else if(l.size()<r.size())
{
if(num<med)
{
l.push(num);
}
else
{
l.push(r.top());
r.pop();
r.push(num);
}
med=(l.top()+r.top())/2.0;
}
else
{
if(num<med)
{
l.push(num);
med=(double)l.top();
}
else
{
r.push(num);
med=(double)r.top();
}
}
}
double findMedian() {
return med;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/