[LeetCode] Moving Average from Data Stream

346. Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Implement the MovingAverage class:

  • MovingAverage(int size) Initializes the object with the size of the window size.
  • double next(int val) Returns the moving average of the last size values of the stream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MovingAverage {
deque<int> dq;
int sum, sz;
public:
MovingAverage(int size):sum(0), sz(size), dq({}) {

}

double next(int val) {
dq.push_back(val);
sum += val;
if(dq.size() > sz) {
sum -= dq.front();
dq.pop_front();
}
return 1. * sum / dq.size();
}
};

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage* obj = new MovingAverage(size);
* double param_1 = obj->next(val);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/moving-average-from-data-stream/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.