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

 

Queue数据结构。
先进先出,当存的数字达到size后,每次要poll掉最老的数。再加上最新的数算一算平均值即可。

细节:
1.存储sum要用long或者double,因为你不断加上int,要是你也用int存的话两个int最大值加一加就已经死了。
2.返回值要求是double也要注意,保证算出来是这个格式的。

 

我的实现:

public class MovingAverage {
    /*
    * @param size: An integer
    */
    private int size;
    // sum要用long,否则你两个int最大值一加就已经超了。
    private double sum;
    private Queue<Integer> queue;
    
    public MovingAverage(int size) {
        // do intialization if necessary
        this.size = size;
        this.sum = 0;
        this.queue = new LinkedList<>();
    }

    /*
     * @param val: An integer
     * @return:  
     */
    public double next(int val) {
        // write your code here
        
        if (queue.size() == size) {
            sum -= queue.poll();
        } 
        sum += val;
        queue.offer(val);
        return sum / queue.size();
    }
}

 

posted @ 2018-09-05 07:49  jasminemzy  阅读(244)  评论(0编辑  收藏  举报