思路:用队列来实现滑动窗口,队列长度就是窗口大小。
class MovingAverage {
private:
int n = 0;
int sum = 0;
queue<int> q;
public:
MovingAverage(int size) {
n = size;
}
double next(int val) {
if (q.size() == n) //队列已满,队首出队,val从队尾入队
{
int tmp = q.front();
q.pop();
q.push(val);
sum = sum - tmp + val;
}
else
{
q.push(val);
sum += val;
}
//当队列未满时,长度是不足n的,取平均值时要除以队列的长度
return (sum * 1.0) / min(n, (int)q.size());
}
};