Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
58 lines (47 loc) · 1.33 KB

346.md

File metadata and controls

58 lines (47 loc) · 1.33 KB

346. Moving Average from Data Stream

Description

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

Thinking Process

  1. Use a queue to keep track of the integers that should be considered to compute average
  2. Keep the sum of the queue as a seperate attribute to avoid traversing the queue every time

Code

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

Complexity

  1. Space complexity is O(size)
  2. Time complexity is O(1) for each next() call