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
题目标签:Design
这道题目让我们设计一个移动平均值的结构,我们有一个input size, 这个size是控制着我们的window。每次都新的数字进来,如果目前的size小于window,那么继续加入。如果新的数字进来,size已经满了,等于window size。那么我们需要把第一个数字去除,然后加入新的数字。可以利用ArrayList来模仿queue实现,add 加入到最后, remove(0) 把第一个数字去除。还要设一个sum, 每次加入,就加入sum, 当满了之后,每次去除,只要从sum里减去。这样就可以避免每一次加入一个数字的时候,都要遍历一次queue来得到所有数字之和。
Java Solution:
Runtime beats 71.48%
完成日期:07/09/2017
关键词:Design
关键点:利用ArrayList来模仿Queue
1 public class MovingAverage { 2 3 ArrayList<Integer> queue; 4 int queue_size; 5 double sum; 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) 8 { 9 queue = new ArrayList<>(size); 10 queue_size = size; 11 sum = 0; 12 } 13 14 public double next(int val) 15 { 16 if(queue.size() == queue_size) // meaning it is full 17 { 18 sum -= queue.get(0); // minus head 19 queue.remove(0); // remove the head 20 } 21 22 queue.add(val); //append the new integer 23 sum += val; // add into sum 24 25 return (sum / queue.size()); 26 } 27 } 28 29 /** 30 * Your MovingAverage object will be instantiated and called as such: 31 * MovingAverage obj = new MovingAverage(size); 32 * double param_1 = obj.next(val); 33 */
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
时间: 2024-12-28 16:11:13