BiruLyu
7/28/2017 - 12:27 AM

346. Moving Average from Data Stream(#).java

public class MovingAverage {
    
    private int count;
    private double sum;
    private int[] data;
    private final int size;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
        this.count = 0;
        this.sum = 0;
        this.data = new int[size];
    }
    
    public double next(int val) {
        if (count < size) {
            sum += val;
            data[count] = val;
            count++;
            return sum / count;
        }
        else {
            int idx = count % size;
            sum += val;
            sum -= data[idx];
            data[idx] = val;
            count++;
            return sum / size;
        }
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */
public class MovingAverage {
    
    private Queue<Integer> q;
    private int capacity;
    private long sum;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        q = new LinkedList<Integer>();
        capacity = size;
        sum = 0;
    }
    
    public double next(int val) {
        if (q.size() == capacity){
            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);
 */