https://leetcode.com/problems/moving-average-from-data-stream/
public class MovingAverage {
/** Initialize your data structure here. */
LinkedList<Integer> queue;
int size;
int total;
public MovingAverage(int size) {
queue = new LinkedList<Integer>();
this.size = size;
total = 0;
}
public double next(int val) {
if(queue.size()<size){
queue.add(val);
total+=val;
return (total+0.0)/queue.size();
}else{
total-=queue.remove(0);
queue.add(val);
total+=val;
return (total+0.0)/size;
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
Using LinkedList to maintain the data structure, keep track of the total value to improve the efficiency
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