码迷,mamicode.com
首页 > 其他好文 > 详细

Moving Average from Data Stream

时间:2017-01-03 08:13:32      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:public   分析   val   size   利用   lin   code   new   nbsp   

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先进先出的特点即可。

 1 public class MovingAverage {
 2     Queue<Integer> q;
 3     double sum = 0;
 4     int size;
 5 
 6     /** Initialize your data structure here. */
 7     public MovingAverage(int s) {
 8         q = new LinkedList();
 9         size = s;
10     }
11 
12     public double next(int val) {
13         if (q.size() == size) {
14             sum = sum - q.poll();
15         }
16         q.offer(val);
17         sum += val;
18         return sum / q.size();
19     }
20 }

 

Moving Average from Data Stream

标签:public   分析   val   size   利用   lin   code   new   nbsp   

原文地址:http://www.cnblogs.com/beiyeqingteng/p/6243672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!