[leetcode]346. Moving Average from Data Stream滑动窗口平均值

Posted 程序媛詹妮弗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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  */

 

以上是关于[leetcode]346. Moving Average from Data Stream滑动窗口平均值的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]346. Moving Average from Data Stream滑动窗口平均值

LeetCode 346. Moving Average from Data Stream (数据流动中的移动平均值)

346. Moving Average from Data Stream - Easy

[LeetCode] 1033. Moving Stones Until Consecutive

[leetcode]Moving Average from Data Stream

LeetCode-Moving Average from Data Stream