zoukankan      html  css  js  c++  java
  • [leetcode]346. Moving Average from Data Stream滑动窗口平均值

    Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

    For 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

    题意:

    给定固定长度的滑动窗口,更新滑动窗口中所有数的平均值。

    思路:

    这种先进先出的特性很适合用queue

    若当前queue的size大于sliding window的长度

    则从queue中remove一个元素

    注意:

    全局变量用下划线_size, _sum是个好的coding style

    代码:

     1 class MovingAverage {
     2     Queue<Integer> _queue = new LinkedList<>();
     3     int _size;
     4     double _sum;
     5 
     6     /** Initialize your data structure here. */
     7     public MovingAverage(int size) {
     8         _size = size;
     9         _sum = 0.0;
    10     }
    11     
    12     public double next(int val) {
    13         _queue.add(val);
    14         _sum = _sum + val;
    15         if(_queue.size() > _size ){
    16             _sum = _sum - _queue.remove();
    17         }
    18         return _sum/_queue.size();
    19     }
    20 }
    21 
    22 /**
    23  * Your MovingAverage object will be instantiated and called as such:
    24  * MovingAverage obj = new MovingAverage(size);
    25  * double param_1 = obj.next(val);
    26  */
  • 相关阅读:
    BZOJ2738 矩阵乘法
    BZOJ3585 mex
    BZOJ1930 [Shoi2003]pacman 吃豆豆
    BZOJ3858 Number Transformation
    vue2.0学习小列子
    vue2.0 tab切换几种方式
    github学习
    只有自己看的懂的vue 二叉树的3级联动
    vuex学习
    vue2.0 MintUI安装和基本使用
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9189707.html
Copyright © 2011-2022 走看看