• 数据流滑动窗口平均值 · sliding window average from data stream


    [抄题]:

    给出一串整数流和窗口大小,计算滑动窗口中所有整数的平均值。

    MovingAverage m = new MovingAverage(3);
    m.next(1) = 1 // 返回 1.00000
    m.next(10) = (1 + 10) / 2 // 返回 5.50000
    m.next(3) = (1 + 10 + 3) / 3 // 返回 4.66667
    m.next(5) = (10 + 3 + 5) / 3 // 返回 6.00000

     [暴力解法]:

    来一个数就存数组,for 循环最近size个数求和取平均返回。

    时间分析:size

    空间分析:n

    [思维问题]:

    不知道为什么要定义全局变量:因为两个函数中都要用。

    提前声明,在函数中分别具体实现。

    [一句话思路]:

    先进先出,用queue实现就行。

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 判断queue尺寸,已经满了,就先拿出来 再放进去。

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    1. 方法中只有实现,没有声明。que = new LinkedList<Integer>();即可

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    n个点,每个点执行一次。不知道queue都是这样吗?下次注意

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [其他解法]:

    前缀和,没有通用性,算了

    1. 时间分析:方便快速求a数组中某一段的和 前缀和做差法 a[k] + a[k + 1] +... + a[j] = s[j] - s[k -1] 时间复杂度降成o(1) 

    [Follow Up]:

    [LC给出的题目变变变]:

    239. Sliding Window Maximum median 一堆数求最值,用堆

    773. Sliding Puzzle 最短路,用bfs

     [代码风格] :

    /  除号两边要打空格

    public class MovingAverage {
        /*
        * @param size: An integer
        */
            private double sum = 0;//
            private int size;
            private int val;
            private Queue<Integer> que;
            
            public MovingAverage(int size) {
            this.size = size;
            que = new LinkedList<Integer>();
        }
    
        /*
         * @param val: An integer
         * @return:  
         */
        public double next(int val) {
            this.val = val;
            this.sum = sum;
            sum += val;
            if (que.size() == size) {
                sum = sum - que.poll();
            }
            que.offer(val);
            
            return sum / que.size();//
        }
    }
    View Code
  • 相关阅读:
    Docker GitLab镜像部署
    Kubernetes集群部署之三ETCD集群部署
    Kubernetes集群部署之二CA证书制作
    Kubernetes集群部署之一系统环境初始化
    docker开源仓库Harbor部署笔记
    git分支
    git高清技能图
    vue+uwsgi+nginx部署路飞学城
    git基础
    git安装与初始化
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8446875.html
Copyright © 2020-2023  润新知