Solution URL
https://leetcode.com/submissions/detail/415226772/
代码
class MovingAverage {
//Ans: Solution
int size;
List<Integer> q = new ArrayList<>();
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
//add the data into list from data steam
q.add(val);
//calculate the sum of last n data in the queue(or all data in the queue)
//decide by the size
int sum = 0;
for(int i = Math.max(0, q.size() - size); i < q.size();i++){
sum += q.get(i);
}
//return the average
return (sum * 1.0) / Math.min(size, q.size());
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/