Moving Average from Data Stream LT346

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
 1 public class MovingAverage {
 2     private Queue<Integer> queue;
 3     private int capacity;
 4     private double sum;
 5     /** Initialize your data structure here. */
 6     public MovingAverage(int size) {
 7         queue = new ArrayDeque<>();
 8         capacity = size;
 9         sum = 0;
10     }
11 
12     public double next(int val) {
13         if(queue.size() == capacity) {
14             sum -= queue.poll();
15         }
16         queue.offer(val);
17         sum += val;
18         return sum/queue.size();
19     }
20 
21     public static void main(String[] args) {
22         int[] nums = {1, 10, 3, 5};
23         MovingAverage movingAverage = new MovingAverage(3);
24         for(int num: nums) {
25             System.out.println(movingAverage.next(num));
26         }
27     }
28 }

 python:

 1 import queue
 2 
 3 class MovingAverage:
 4     def __init__(self, capacity):
 5         self.capacity = capacity
 6         self.sum = 0
 7         self.window = queue.Queue(capacity)
 8         
 9         
10     def next(self, num):
11         if self.window.full():
12             self.sum -= self.window.get()
13             
14         self.sum += num
15         self.window.put(num)
16         return self.sum/self.window.qsize()
17     
18 def test():
19         test_data = [1, 10, 3, 5]
20         test_subject = MovingAverage(3)
21         for num in test_data:
22             print (test_subject.next(num))
23             
24 if __name__ == '__main__':
25         test()

 

posted on 2019-03-02 20:29  一直走在路上  阅读(121)  评论(0)    收藏  举报

导航