[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 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 题目总结

你可能感兴趣的:([LeetCode] 346. Moving Average from Data Stream)