346. Moving Average from Data Stream - Easy

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

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

 

use queue to keep track of all the numbers in a window

time: O(1), space: O(k)  -- k: size of the window

class MovingAverage {

    /** Initialize your data structure here. */
    private Queue<Integer> q;
    private int size;
    private double sum;
    
    public MovingAverage(int size) {
        q = new LinkedList<>();
        this.size = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() == size) {
            sum -= q.poll();
        }
        q.offer(val);
        sum += val;
        return (double)(sum / q.size());
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

 

posted @ 2019-08-11 14:17  fatttcat  阅读(112)  评论(0编辑  收藏  举报