346. Moving Average from Data Stream
by Botao Xiao
346. Moving Average from Data Stream
Question
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
Solution
- Method 1: Array
```Java
class MovingAverage {
private int[] arr;
private int size;
private int index;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.size = size;
this.arr = new int[size];
}
public double next(int val) {
arr[(index++) % this.size] = val;
double sum = 0D;
for(int v : arr)
sum += v;
return sum / (index <= size ? index: this.size);
}
}
/**
- Your MovingAverage object will be instantiated and called as such:
- MovingAverage obj = new MovingAverage(size);
- double param_1 = obj.next(val); */ ```
- Method 2: Queue
class MovingAverage { private Queue<Integer> q; private int size; private double sum; /** Initialize your data structure here. */ public MovingAverage(int size) { this.size = size; q = new LinkedList<>(); } public double next(int val) { q.offer(val); sum += val; while(!q.isEmpty() && q.size() > size){ sum -= q.poll(); } return sum / q.size(); } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
Subscribe via RSS