解法一:pbds
直接暴力走就完事了,每次求平均数O(k),基本也就是无敌吧。
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef pair<int, int> P;
typedef long long ll;
class MKAverage {
tree<P, null_type, less<P>, rb_tree_tag, tree_order_statistics_node_update> t;
queue<P> q;
int m, k;
int ct = 0;
public:
MKAverage(int m, int k) {
this->m = m;
this->k = k;
}
void addElement(int num) {
ct += 1;
q.push(P(num, ct));
t.insert(P(num, ct));
if(t.size() > m)
{
t.erase(q.front());
q.pop();
}
}
int calculateMKAverage() {
if(t.size() < m)return -1;
ll ret = 0;
for(int i=k;i<m-k;i++)
ret += t.find_by_order(i)->first;
return ret/(m-2*k);
}
};
/**
* Your MKAverage object will be instantiated and called as such:
* MKAverage* obj = new MKAverage(m, k);
* obj->addElement(num);
* int param_2 = obj->calculateMKAverage();
*/
解法二:排序
直接用vector把每个数存好,每次对后m个数排序即可。要注意的是,不能对原数组排序,不然顺序会乱。复杂度为O(nmlogm),稍高,但也能过。