Friday, August 24, 2018

346. Moving Average from Data Stream

346Moving Average from Data Stream
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
----------------------
class MovingAverage {
    
    private int[] buffer;
    private int pointer;
    private int sum;
    private int size;
    private int sofar;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
        buffer = new int[size];
        pointer = 0;
        sum = 0;
        sofar = 0;
    }
    
    public double next(int val) {
        sum -= buffer[pointer];
        sum += val;
        buffer[pointer] = val;
        pointer++;
        pointer %= size;
        
        if (sofar < size) sofar++;
        
        return (double)sum / sofar;
    }
}

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

No comments:

Post a Comment