-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathdata-stream-median(AC).cpp
More file actions
41 lines (39 loc) · 1 KB
/
data-stream-median(AC).cpp
File metadata and controls
41 lines (39 loc) · 1 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
#include <queue>
using namespace std;
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The median of numbers
*/
vector<int> medianII(vector<int> &nums) {
vector<int> &a = nums;
int n = a.size();
// The smaller half
priority_queue<int, vector<int>, less<int> > small;
// The larger half
priority_queue<int, vector<int>, greater<int> > large;
int i;
vector<int> ans;
small.push(INT_MIN);
large.push(INT_MAX);
int vs, vl;
for (i = 0; i < n; ++i) {
if (i & 1) {
large.push(a[i]);
} else {
small.push(a[i]);
}
vs = small.top();
vl = large.top();
if (vs > vl) {
small.pop();
small.push(vl);
large.pop();
large.push(vs);
}
ans.push_back(small.top());
}
return ans;
}
};