-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRunning median.cpp
More file actions
61 lines (55 loc) · 1.37 KB
/
Running median.cpp
File metadata and controls
61 lines (55 loc) · 1.37 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
vector<double> runningMedian(vector<int> arr) {
priority_queue<double> s;
priority_queue<double,vector<double>,greater<double> > g;
double med = arr[0];
s.push(arr[0]);
vector<double> res;
res.emplace_back(med);
int n=arr.size();
for (int i=1; i <n ; i++)
{
double x = arr[i];
// case1(left side heap has more elements)
if (s.size() > g.size())
{
if (x < med)
{
g.push(s.top());
s.pop();
s.push(x);
}
else
g.push(x);
med = (s.top() + g.top())/2.0;
}
// case2(both heaps are balanced)
else if (s.size()==g.size())
{
if (x < med)
{
s.push(x);
med = (double)s.top();
}
else
{
g.push(x);
med = (double)g.top();
}
}
// case3(right side heap has more elements)
else
{
if (x > med)
{
s.push(g.top());
g.pop();
g.push(x);
}
else
s.push(x);
med = (s.top() + g.top())/2.0;
}
res.emplace_back(med);
}
return res;
}