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  */

     

  • 相关阅读:
    模拟费用流学习笔记
    爬山游记
    基数排序板子
    webim
    centos9 重启网络
    Linux虚拟机桥接模式下ping不通自己配置的网关
    win7怎样开启loopback接口(环回网卡)
    在CentOS上配置SAMBA共享目录
    linux间scp拷贝文件夹
    nginx配置http和https可同时访问方法
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5767544.html
Copyright © 2011-2022 走看看