Moving Average from Data Stream LT346

时间:2022-09-25 08:50:56
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
Idea 1. Sliding window, we need to store elements and poll out the first element when reaching the window size, it looks like queue strucutre fits our needs, it's first-in-first-out.
Time complexity: O(n)
Space complexity: O(k) k is the size of the sliding window
 public class MovingAverage {
private Queue<Integer> queue;
private int capacity;
private double sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
queue = new ArrayDeque<>();
capacity = size;
sum = 0;
} public double next(int val) {
if(queue.size() == capacity) {
sum -= queue.poll();
}
queue.offer(val);
sum += val;
return sum/queue.size();
} public static void main(String[] args) {
int[] nums = {1, 10, 3, 5};
MovingAverage movingAverage = new MovingAverage(3);
for(int num: nums) {
System.out.println(movingAverage.next(num));
}
}
}

python:

 import queue

 class MovingAverage:
def __init__(self, capacity):
self.capacity = capacity
self.sum = 0
self.window = queue.Queue(capacity) def next(self, num):
if self.window.full():
self.sum -= self.window.get() self.sum += num
self.window.put(num)
return self.sum/self.window.qsize() def test():
test_data = [1, 10, 3, 5]
test_subject = MovingAverage(3)
for num in test_data:
print (test_subject.next(num)) if __name__ == '__main__':
test()