-
Notifications
You must be signed in to change notification settings - Fork 0
/
findMedianInAStream.cpp
90 lines (81 loc) · 2 KB
/
findMedianInAStream.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
79
80
81
82
83
84
85
86
87
88
89
90
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
priority_queue<int, vector<int>, greater<int>> pqmin;
priority_queue<int, vector<int>> pqmax;
//Function to insert heap.
void insertHeap(int &x)
{
if(pqmin.size() == pqmax.size()) {
if(pqmax.size() == 0) {
pqmax.push(x);
return;
}
if(x < pqmax.top()) {
pqmax.push(x);
}
else {
pqmin.push(x);
}
} else {
if(pqmax.size() > pqmin.size()) {
if(x >= pqmax.top()) {
pqmin.push(x);
} else {
int temp = pqmax.top();
pqmax.pop();
pqmin.push(temp);
pqmax.push(x);
}
} else {
if(x <= pqmin.top()) {
pqmax.push(x);
} else {
int temp = pqmin.top();
pqmin.pop();
pqmax.push(temp);
pqmin.push(x);
}
}
}
}
//Function to balance heaps.
void balanceHeaps()
{
return;
}
//Function to return Median.
double getMedian()
{
if(pqmax.size() == pqmin.size()) {
return (pqmin.top() + pqmax.top())/2.0;;
} else if (pqmin.size() > pqmax.size()) {
return pqmin.top();
} else {
return pqmax.top();
}
}
};
// { Driver Code Starts.
int main()
{
int n, x;
int t;
cin>>t;
while(t--)
{
Solution ob;
cin >> n;
for(int i = 1;i<= n; ++i)
{
cin >> x;
ob.insertHeap(x);
cout << floor(ob.getMedian()) << endl;
}
}
return 0;
} // } Driver Code Ends