Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For 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:
MovingAverage(int size){
vect.resize(size,0);
count=0;
sum=0;
full=0;
}
double next(int val){
int sz=vect.size();
if(count==sz){
count=0;
full=1;
}
sum-=vect[count];
vect[count]=val;
sum+=val;
count++;
return full==1?sum/sz:sum/count;
}
private:
vector<int> vect;
int count;
int sum;
bool full;
};