题目描述:
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example:
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
class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
k=size;
sum=0;
}
double next(int val) {
if(dq.size()<k)
{
dq.push_back(val);
sum+=val;
}
else
{
sum+=val;
sum-=dq.front();
dq.pop_front();
dq.push_back(val);
}
return sum/dq.size();
}
private:
deque<int> dq;
int k;
double sum;
};