346. Moving Average from Data Stream - Easy
Posted fatttcat
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了346. Moving Average from Data Stream - Easy相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 346. Moving Average from Data Stream ??????????????????????????????
[leetcode]346. Moving Average from Data Stream滑动窗口平均值
LeetCode 346. Moving Average from Data Stream (数据流动中的移动平均值)
Moving Average from Data Stream