LeetCode Moving Average from Data Stream

时间:2022-09-11 08:22:08

原题链接在这里:https://leetcode.com/problems/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

题解:

维护一个queue, 当queue的size已经等于size时若是继续加新的val就需要poll值.

Time Complexity: MovingAverage(size) O(1), next(val) O(1).

Space: O(size) 需要维护queue

AC Java:

 public class MovingAverage {

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