Description
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
Thinking Process
- Use a queue to keep track of the integers that should be considered to compute average
- Keep the sum of the queue as a seperate attribute to avoid traversing the queue every time
Code
public class MovingAverage {
Queue<Integer> que;
int len;
int sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
que = new LinkedList<>();
len = size;
sum = 0;
}
public double next(int val) {
if(que.size() < len){
sum += val;
que.add(val);
return (double) sum / que.size();
}else{
sum = sum - que.poll() + val;
que.add(val);
return (double) sum / len;
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
Complexity
- Space complexity is O(size)
- Time complexity is O(1) for each next() call