标签: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