Leetcode 346. Moving Average from Data Stream (Easy) (cpp)
Tag: Design, Queue
Difficulty: Easy
/*
346. Moving Average from Data Stream (Easy)
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:
/** Initialize your data structure here. */
int _size = 0, sum = 0;
deque<int> d;
MovingAverage(int size) {
_size = size;
}
double next(int val) {
while (d.size() >= _size) {
sum -= d.front();
d.pop_front();
}
sum += val;
d.push_back(val);
return (double)sum / d.size();
}
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/