LeetCode-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

这道题目让我们设计一个移动平均值的结构,我们有一个input size, 这个size是控制着我们的window。每次都新的数字进来,如果目前的size小于window,那么继续加入。如果新的数字进来,size已经满了,等于window size。那么我们需要把第一个数字去除,然后加入新的数字。可以利用ArrayList来模仿queue实现,add 加入到最后, remove(0) 把第一个数字去除。还要设一个sum, 每次加入,就加入sum, 当满了之后,每次去除,只要从sum里减去。这样就可以避免每一次加入一个数字的时候,都要遍历一次queue来得到所有数字之和。

public class MovingAverage {
    Queue<Integer> queue;
    int n;
    int sum;
     
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        queue = new LinkedList<>();
        n = size;
        sum = 0;
    }
     
    public double next(int val) {
        queue.offer(val);
        double result = 0;
        sum += val;
        if (queue.size() <= n) {
            result = (double) sum / queue.size();
        } else {
            int remove = queue.poll();
            sum -= remove;
            result = (double) sum / n;
        }
         
        return result;
    }
}
 
/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

猜你喜欢

转载自www.cnblogs.com/incrediblechangshuo/p/9252044.html
今日推荐