LeetCode 480. Sliding Window Median

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
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
vector<double> medians;
unordered_map<int, int> hash_table; // deleted element -> frequency.
priority_queue<int> lo;
priority_queue<int, vector<int>, greater<int>> hi;
int i = 0;
while (i < k)
lo.push(nums[i++]);
for (int j = 0; j < k / 2; j++) {
hi.push(lo.top());
lo.pop();
}

while (true) {
medians.push_back(k & 1 ? lo.top() : ((double) lo.top() + (double) hi.top()) * 0.5);
if (i >= nums.size())
break;
int out_num = nums[i - k],
in_num = nums[i++],
balance = 0;

balance += (out_num <= lo.top() ? -1 : 1);
hash_table[out_num]++;

if (!lo.empty() && in_num <= lo.top()) {
balance++;
lo.push(in_num);
} else {
balance--;
hi.push(in_num);
}

if (balance < 0) {
lo.push(hi.top());
hi.pop();
balance++;
}
if (balance > 0) {
hi.push(lo.top());
lo.pop();
balance--;a
}

while (hash_table[lo.top()]) {
hash_table[lo.top()]--;
lo.pop();
}
while (!hi.empty() && hash_table[hi.top()]) {
hash_table[hi.top()]--;
hi.pop();
}
}
return medians;
}
};