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

链接:

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  */
原文地址:https://www.cnblogs.com/panini/p/6540610.html