346. 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

可以发现规律,数字长度不能超过定义的初始大小, 否则舍弃最开始的部分, 很明显要用到先进先出的队列。

public class MovingAverage { 
     Queue queue;
     int queue_size;
     double sum = 0;
     public MovingAverage(int size) {
               queue = new LinkedList<>();
               queue_size = size;
     }
     public double next(int val) {
               sum += val;
               queue.offer(val);
               if(queue.size() > queue_size){
                       sum -= queue.poll();
                       return sum/queue_size;
               }else{
                       return sum/queue.size();
               }
     }
}

你可能感兴趣的:(346. Moving Average from Data Stream)