congr / world

2 stars 1 forks source link

LeetCode : 346. Moving Average from Data Stream #470

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/moving-average-from-data-stream/

image

congr commented 5 years ago
class MovingAverage {
    int size;
    List<Integer> list;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
        this.list = new ArrayList();
    }

    public double next(int val) {
        list.add(val);

        int div = Math.min(list.size(), size);
        int sum = 0;
        for (int i = list.size() - 1, j = 0; j < div; j++) 
            sum += list.get(i-j);

        return (double)sum / div;
    }
}

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

Faster code

class MovingAverage {
    int size;
    int pSum;
    Queue<Integer> q;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
        this.q = new LinkedList();
    }

    public double next(int val) {
        if (q.size() >= size) pSum -= q.remove();

        q.add(val);
        pSum += val;

        return (double)pSum / q.size();
    }
}

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