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

Moving Average from Data Stream

时间:2016-07-21 14:29:08      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

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


public class MovingAverage {

    private int size;
    private double sum;
    private ArrayDeque<Integer> queue;
    public MovingAverage(int size) {
        this.size = size;
        this.sum = 0;
        this.queue = new ArrayDeque<Integer>();
    }

    public double next(int val) {
        if (queue.size() == size) {
            sum -= queue.remove();
        }
        queue.offer(val);
        sum += val;
        return sum / queue.size();
    }
}

https://discuss.leetcode.com/topic/50122/100-java-solution-with-deque

deque:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html

 

Moving Average from Data Stream

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5691336.html

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