forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
73 lines (68 loc) · 1.76 KB
/
Solution.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
class MKAverage {
public:
MKAverage(int m, int k) {
this->m = m;
this->k = k;
}
void addElement(int num) {
if (lo.empty() || num <= *lo.rbegin()) {
lo.insert(num);
} else if (hi.empty() || num >= *hi.begin()) {
hi.insert(num);
} else {
mid.insert(num);
s += num;
}
q.push(num);
if (q.size() > m) {
int x = q.front();
q.pop();
if (lo.find(x) != lo.end()) {
lo.erase(lo.find(x));
} else if (hi.find(x) != hi.end()) {
hi.erase(hi.find(x));
} else {
mid.erase(mid.find(x));
s -= x;
}
}
while (lo.size() > k) {
int x = *lo.rbegin();
lo.erase(prev(lo.end()));
mid.insert(x);
s += x;
}
while (hi.size() > k) {
int x = *hi.begin();
hi.erase(hi.begin());
mid.insert(x);
s += x;
}
while (lo.size() < k && mid.size()) {
int x = *mid.begin();
mid.erase(mid.begin());
s -= x;
lo.insert(x);
}
while (hi.size() < k && mid.size()) {
int x = *mid.rbegin();
mid.erase(prev(mid.end()));
s -= x;
hi.insert(x);
}
}
int calculateMKAverage() {
return q.size() < m ? -1 : s / (q.size() - k * 2);
}
private:
int m, k;
long long s = 0;
queue<int> q;
multiset<int> lo, mid, hi;
};
/**
* Your MKAverage object will be instantiated and called as such:
* MKAverage* obj = new MKAverage(m, k);
* obj->addElement(num);
* int param_2 = obj->calculateMKAverage();
*/