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
题意:
给定固定长度的滑动窗口,更新滑动窗口中所有数的平均值。
思路:
这种先进先出的特性很适合用queue
若当前queue的size大于sliding window的长度
则从queue中remove一个元素
注意:
全局变量用下划线_size, _sum是个好的coding style
代码:
1 class MovingAverage { 2 Queue<Integer> _queue = new LinkedList<>(); 3 int _size; 4 double _sum; 5 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) { 8 _size = size; 9 _sum = 0.0; 10 } 11 12 public double next(int val) { 13 _queue.add(val); 14 _sum = _sum + val; 15 if(_queue.size() > _size ){ 16 _sum = _sum - _queue.remove(); 17 } 18 return _sum/_queue.size(); 19 } 20 } 21 22 /** 23 * Your MovingAverage object will be instantiated and called as such: 24 * MovingAverage obj = new MovingAverage(size); 25 * double param_1 = obj.next(val); 26 */