Moving Average from Data Stream -- LeetCode

时间:2023-03-08 20:16:19

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 {
private:
queue<int> numsInWindow;
int windowSize;
double lastAverage;
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
windowSize = size;
} double next(int val) {
if (numsInWindow.empty()) {
numsInWindow.push(val);
lastAverage = (double) val;
}
else if (numsInWindow.size() < windowSize) {
double total = lastAverage * numsInWindow.size();
numsInWindow.push(val);
lastAverage = (total + val) / numsInWindow.size();
}
else {
double total = lastAverage * numsInWindow.size();
total -= numsInWindow.front();
numsInWindow.pop();
numsInWindow.push(val);
lastAverage = (total + val) / numsInWindow.size();
}
return lastAverage;
}
}; /**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/