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.

    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

    数据流中的平均值。题意很简单,就是不断接受来自数据流的数字,算平均值。如果接收的数字的个数大于规定的size,则开始弹出队首元素。

    时间O(n)

    空间O(n)

    Java实现

     1 class MovingAverage {
     2     private Queue<Integer> queue;
     3     private double sum = 0;
     4     private int size;
     5 
     6     /** Initialize your data structure here. */
     7     public MovingAverage(int size) {
     8         this.size = size;
     9         queue = new LinkedList<>();
    10     }
    11     
    12     public double next(int val) {
    13         if (queue.size() == size) {
    14             sum -= queue.poll();
    15         }
    16         queue.offer(val);
    17         sum += val;
    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  */

    LeetCode 题目总结

  • 相关阅读:
    mongodb
    python中读取文件的read、readline、readlines方法区别
    uva 129 Krypton Factor
    hdu 4734
    hdu 5182 PM2.5
    hdu 5179 beautiful number
    hdu 5178 pairs
    hdu 5176 The Experience of Love
    hdu 5175 Misaki's Kiss again
    hdu 5174 Ferries Wheel
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13430979.html
Copyright © 2011-2022 走看看