-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path072_Running Median.cpp
56 lines (45 loc) · 1.19 KB
/
072_Running Median.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
// Time Complexity -> O(N * log(N))
// Space Complexity -> O(N)
#include <queue>
void findMedian(int *arr, int n) {
// Write your code here
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
for (int i = 0; i < n; ++i) {
if (maxHeap.empty() and minHeap.empty())
maxHeap.push(arr[i]);
else {
if (arr[i] > maxHeap.top()) {
minHeap.push(arr[i]);
} else {
maxHeap.push(arr[i]);
}
}
int maxSize = maxHeap.size();
int minSize = minHeap.size();
if (maxSize - minSize == 2 or maxSize - minSize == -2) {
if (maxSize > minSize) {
int cur = maxHeap.top();
maxHeap.pop();
minHeap.push(cur);
--maxSize;
++minSize;
} else {
int cur = minHeap.top();
minHeap.pop();
maxHeap.push(cur);
--minSize;
++maxSize;
}
}
// median
if (maxSize > minSize)
cout << maxHeap.top() << ' ';
else if (minSize > maxSize)
cout << minHeap.top() << ' ';
else {
int ans = (maxHeap.top() + minHeap.top()) >> 1;
cout << ans << ' ';
}
}
}