您的位置:首页 > 其它

346. Moving Average from Data Stream

2017-03-13 04:09 429 查看
题目:

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

链接:

https://leetcode.com/problems/moving-average-from-data-stream/?tab=Description

3/12/2017

第19行,返回需要是double型

1 public class MovingAverage {
2     Queue<Integer> q;
3     int qSize;
4     int sum = 0;
5
6     /** Initialize your data structure here. */
7     public MovingAverage(int size) {
8         q = new LinkedList<Integer>();
9         qSize = size;
10     }
11
12     public double next(int val) {
13         q.add(val);
14         sum += val;
15         if (q.size() > qSize) {
16             int removed = q.remove();
17             sum -= removed;
18         }
19         return sum * 1.0 / q.size();
20     }
21 }
22
23 /**
24  * Your MovingAverage object will be instantiated and called as such:
25  * MovingAverage obj = new MovingAverage(size);
26  * double param_1 = obj.next(val);
27  */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: