Monday, July 25, 2016

LeetCode [346] Moving Average from Data Stream

 346. Moving Average from Data Stream

Easy

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MovingAverage {
    Deque<Integer> que = new ArrayDeque<>();
    int w, s;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        w = size;
        s = 0;
    }
    
    public double next(int val) {
        if(que.size()==w){
            s -= que.pollFirst();
        }
        que.addLast(val);
        s += val;
        return (double)s/que.size();
    }
}

/**
 * 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