Moving Average from Data Stream LT346

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
  Idea 1. Sliding window, we need to store elements and poll out the first element when reaching the window size, it looks like queue strucutre fits our needs, it's first-in-first-out. Time complexity: O(n) Space complexity: O(k) k is the size of the sliding window
 1 public class MovingAverage {
 2     private Queue<Integer> queue;
 3     private int capacity;
 4     private double sum;
 5     /** Initialize your data structure here. */
 6     public MovingAverage(int size) {
 7         queue = new ArrayDeque<>();
 8         capacity = size;
 9         sum = 0;
10     }
11 
12     public double next(int val) {
13         if(queue.size() == capacity) {
14             sum -= queue.poll();
15         }
16         queue.offer(val);
17         sum += val;
18         return sum/queue.size();
19     }
20 
21     public static void main(String[] args) {
22         int[] nums = {1, 10, 3, 5};
23         MovingAverage movingAverage = new MovingAverage(3);
24         for(int num: nums) {
25             System.out.println(movingAverage.next(num));
26         }
27     }
28 }

 

上一篇:监控Linux


下一篇:第六次试验