zoukankan      html  css  js  c++  java
  • lintcode642

    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();
        }
    }
  • 相关阅读:
    线程安全的简单理解
    单链表 之 判断两链表是否交叉
    React组件间的通信
    input type=file美化
    Array.prototype.slice.call(arguments)
    ES5 数组方法every和some
    nodejs学习之表单提交(1)
    ES5 数组方法reduce
    ES5 数组方法map
    ES5 数组方法forEach
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9589952.html
Copyright © 2011-2022 走看看