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

346. Moving Average from Data Stream - Easy

时间:2019-08-11 15:23:48      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:str   from   anti   example   nbsp   link   this   off   new   

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

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

 

use queue to keep track of all the numbers in a window

time: O(1), space: O(k)  -- k: size of the window

class MovingAverage {

    /** Initialize your data structure here. */
    private Queue<Integer> q;
    private int size;
    private double sum;
    
    public MovingAverage(int size) {
        q = new LinkedList<>();
        this.size = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() == size) {
            sum -= q.poll();
        }
        q.offer(val);
        sum += val;
        return (double)(sum / q.size());
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

 

346. Moving Average from Data Stream - Easy

标签:str   from   anti   example   nbsp   link   this   off   new   

原文地址:https://www.cnblogs.com/fatttcat/p/11334894.html

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