-
Notifications
You must be signed in to change notification settings - Fork 0
/
medianStream.cpp
56 lines (43 loc) · 1.04 KB
/
medianStream.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
//
// Created by Ankush on 31/05/21., median in a stream of integers
//
#include <iostream>
#include <string>
#include <queue>
using namespace std;
priority_queue<int> maxHeap;
priority_queue<int,vector<int>, greater<int>> minHeap;
int getMedianFromStream(int X) {
if (minHeap.empty()) {
minHeap.push(X);
} else {
if (minHeap.top() < X) {
minHeap.push(X);
} else if (maxHeap.top() > X) {
maxHeap.push(X);
}
}
if (maxHeap.size()>minHeap.size()+1) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
if (minHeap.size()>maxHeap.size()+1) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
if (minHeap.size() == maxHeap.size()) {
return (minHeap.top()+maxHeap.top())/2;
} else {
if (maxHeap.size()>minHeap.size()) {
return maxHeap.top();
} else {
return minHeap.top();
}
}
}
//int main() {
//
// //MedianStream ms;
// cout<<getMedianFromStream(1);
// return 0;
//}