这是一道locked题目
这是一道esay题,主要使用一个data(queue<int>)保存数据 和 sum(int)记录当前queue中元素之和。调用next函数的时候需要保证queue的大小为size,所以queue满的时候pop front,同时sum要减去即将被pop出的元素的值。然后push新的元素到queue,更新sum的值。返回值只需 sum / data/size(), 但要把sum和size都强制类型转换为double. That's it!
class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
this->size = size;
sum = 0;
}
double next(int val) {
if (data.size() == size) {
sum -= data.front();
data.pop();
}
data.push(val);
sum += val;
return (double)sum / (double)data.size();
}
private:
int sum;
int size = 0;
queue<int> data;
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/