forked from abbh07/DataStructure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RunningMedian.cpp
78 lines (71 loc) · 1.26 KB
/
RunningMedian.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
74
75
76
77
78
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct comparator
{
bool operator()(int i,int j)
{
return i>j;
}
};
priority_queue<int, vector<int>, comparator> minheap;
priority_queue<int, vector<int> > maxheap;
void insert(int num)
{
if(maxheap.empty() || num < maxheap.top())
{
maxheap.push(num);
}
else
{
minheap.push(num);
}
}
void rebalance()
{
int diff = maxheap.size() - minheap.size();
if( diff >= 2)
{
minheap.push(maxheap.top());
maxheap.pop();
}
else if( diff <= -2)
{
maxheap.push(minheap.top());
minheap.pop();
}
}
double getMedian()
{
double median;
if(maxheap.size() == minheap.size())
{
median = ((double)minheap.top() + maxheap.top())/2;
}
else if(maxheap.size() > minheap.size())
{
median = maxheap.top();
}
else if(minheap.size() > maxheap.size())
{
median = minheap.top();
}
return median;
}
int main()
{
int n;
scanf("%d",&n);
int num;
while(n--)
{
scanf("%d",&num);
insert(num);
rebalance();
double med = getMedian();
printf("%.1f\n",med);
}
return 0;
}