346. 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.

For 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

Solution

(1) Java

class MovingAverage {

    private int capacity = 0;
    private Deque<Integer> q = null;
    private int currentSum = 0;

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

    public double next(int val) {
        if (q.size() != capacity) {
            currentSum += val;
        } else {
            int num = q.poll();
            currentSum += val - num;
        }
        q.offer(val);
        return ((double)currentSum)/q.size();
    }
}

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

(2) Python

class MovingAverage:

    def __init__(self, size):
        """
        Initialize your data structure here.
        :type size: int
        """
        self.q = collections.deque(maxlen=size)


    def next(self, val):
        """
        :type val: int
        :rtype: float
        """
        self.q.append(val)
        return (float(sum(self.q)))/len(self.q)



# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)

(3) Scala



results matching ""

    No results matching ""