• 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();
        }
    }
  • 相关阅读:
    c3p0连接池c3p0-config.xml配置文件各属性的意义
    MVC案例-架构分析
    jsp中文乱码
    JSP标签
    JSP_include指令
    JavaWeb_请求转发
    JavaWeb_域对象的属性操作
    JavaWeb_JSP语法
    345. Reverse Vowels of a String
    541. Reverse String II
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9589952.html
Copyright © 2020-2023  润新知