yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #346. Moving Average from Data Stream #270

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class MovingAverage {
    private int[] window;
    private double sum;
    private int n, insert;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        window = new int[size];
        sum = 0;
        insert = 0;
    }

    public double next(int val) {
        if (n < window.length) n++;
        sum -= window[insert];
        sum += val;
        window[insert] = val;
        insert = (insert + 1) % window.length;

        return (double)sum / n;
    }
}

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

With Queue:

class MovingAverage {
    private Queue<Integer> queue;
    private double sum;
    private int n, len;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        queue = new LinkedList<>();
        sum = 0;
        len = size;
    }

    public double next(int val) {
        if (queue.size() == len) {
            sum -= queue.poll();
        }

        queue.add(val);
        sum += val;

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

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