Leetcode: 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. 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 method:
1 public class MovingAverage { 2 Queue<Integer> queue; 3 int capacity; 4 int sum; 5 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) { 8 queue = new LinkedList<Integer>(); 9 capacity = size; 10 sum = 0; 11 } 12 13 public double next(int val) { 14 if (queue.size() == capacity) { 15 sum -= queue.poll(); 16 } 17 sum += val; 18 queue.offer(val); 19 return (double)sum/queue.size(); 20 } 21 } 22 23 /** 24 * Your MovingAverage object will be instantiated and called as such: 25 * MovingAverage obj = new MovingAverage(size); 26 * double param_1 = obj.next(val); 27 */
Array method: 非常聪明
1 public class MovingAverage { 2 private int [] window; 3 private int n, insert; 4 private long sum; 5 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) { 8 window = new int[size]; 9 insert = 0; 10 sum = 0; 11 } 12 13 public double next(int val) { 14 if (n < window.length) n++; 15 sum -= window[insert]; 16 sum += val; 17 window[insert] = val; 18 insert = (insert + 1) % window.length; 19 20 return (double)sum / n; 21 } 22 }