Thursday, May 9, 2019

Lintcode 642. 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.

Example

Example 1:
MovingAverage m = new MovingAverage(3);
m.next(1) = 1 // return 1.00000
m.next(10) = (1 + 10) / 2 // return 5.50000
m.next(3) = (1 + 10 + 3) / 3 // return 4.66667
m.next(5) = (10 + 3 + 5) / 3 // return 6.00000

Code (Java):
public class MovingAverage {
    /*
    * @param size: An integer
    */
    private Deque<Integer> nums;
    private long sum;
    private int windowSize;
    public MovingAverage(int size) {
        // do intialization if necessary
        this.nums = new LinkedList<>();
        this.sum = 0;
        this.windowSize = size;
    }

    /*
     * @param val: An integer
     * @return:  
     */
    public double next(int val) {
        // write your code here
        sum += val;
        nums.addLast(val);
        if (nums.size() > windowSize) {
            int headVal = nums.removeFirst();
            sum -= headVal;
        }

        return (double) sum / nums.size();
    }
}

No comments:

Post a Comment