给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。
示例:
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
public class MovingAverage {
/** Initialize your data structure here. */
public MovingAverage(int size) {
}
public double Next(int val) {
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.Next(val);
*/
class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
}
double next(int val) {
}
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage* obj = new MovingAverage(size);
* double param_1 = obj->next(val);
*/
class MovingAverage {
public:
/** Initialize your data structure here. */
queue<int> q;
int size;
MovingAverage(int size)
{
this->size = size;
}
double next(int val)
{
if (q.size() == size)
{
q.pop();
q.push(val);
}
else
{
q.push(val);
}
queue<int> cur = q;
int curSize = q.size();
double cnt = 0;
while (!cur.empty())
{
cnt += cur.front();
cur.pop();
}
return cnt / curSize;
}
};