zoukankan      html  css  js  c++  java
  • Moving Average from Data Stream -- LeetCode

    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
     1 class MovingAverage {
     2 private:
     3     queue<int> numsInWindow;
     4     int windowSize;
     5     double lastAverage;
     6 public:
     7     /** Initialize your data structure here. */
     8     MovingAverage(int size) {
     9         windowSize = size;
    10     }
    11     
    12     double next(int val) {
    13         if (numsInWindow.empty()) {
    14             numsInWindow.push(val);
    15             lastAverage = (double) val;
    16         }
    17         else if (numsInWindow.size() < windowSize) {
    18             double total = lastAverage * numsInWindow.size();
    19             numsInWindow.push(val);
    20             lastAverage = (total + val) / numsInWindow.size();
    21         }
    22         else {
    23             double total = lastAverage * numsInWindow.size();
    24             total -= numsInWindow.front();
    25             numsInWindow.pop();
    26             numsInWindow.push(val);
    27             lastAverage = (total + val) / numsInWindow.size();
    28         }
    29         return lastAverage;
    30     }
    31 };
    32 
    33 /**
    34  * Your MovingAverage object will be instantiated and called as such:
    35  * MovingAverage obj = new MovingAverage(size);
    36  * double param_1 = obj.next(val);
    37  */

     

  • 相关阅读:
    使用a标签制作tooltips
    使用editorconfig配置你的编辑器
    JointJS绘制流程图
    用highcharts展现你的数据
    css段落首字母下沉
    sklearn框架的系统学习
    numpy删除二维数据矩阵的行和列
    sklearn中机器学习算法评价指标
    sklearn调用逻辑回归算法
    sklearn调用多项式回归
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5767544.html
Copyright © 2011-2022 走看看