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

时间:2021-06-08 19:53:45

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

题目标签:Design

  这道题目让我们设计一个移动平均值的结构,我们有一个input size, 这个size是控制着我们的window。每次都新的数字进来,如果目前的size小于window,那么继续加入。如果新的数字进来,size已经满了,等于window size。那么我们需要把第一个数字去除,然后加入新的数字。可以利用ArrayList来模仿queue实现,add 加入到最后, remove(0) 把第一个数字去除。还要设一个sum, 每次加入,就加入sum, 当满了之后,每次去除,只要从sum里减去。这样就可以避免每一次加入一个数字的时候,都要遍历一次queue来得到所有数字之和。

Java Solution:

Runtime beats 71.48%

完成日期:07/09/2017

关键词:Design

关键点:利用ArrayList来模仿Queue

 public class MovingAverage {

     ArrayList<Integer> queue;
int queue_size;
double sum;
/** Initialize your data structure here. */
public MovingAverage(int size)
{
queue = new ArrayList<>(size);
queue_size = size;
sum = 0;
} public double next(int val)
{
if(queue.size() == queue_size) // meaning it is full
{
sum -= queue.get(0); // minus head
queue.remove(0); // remove the head
} queue.add(val); //append the new integer
sum += val; // add into sum return (sum / queue.size());
}
} /**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/

参考资料:N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List