ID | Title | Difficulty | |
---|---|---|---|
Loading... |
346. Moving Average from Data Stream
Easy
LeetCode
Array, Design, Queue, Data Stream
Problem
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage class:
MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream.
Example 1:
Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]
Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Code
class MovingAverage {
int size;
Queue<Integer> queue;
double sum;
public MovingAverage(int size) {
this.size = size;
this.sum = 0;
this.queue = new LinkedList<>();
}
public double next(int val) {
this.sum += val;
this.queue.offer(val);
if(queue.size() > this.size) {
sum -= queue.poll();
}
return sum / this.queue.size();
}
}
按 <- 键看上一题!
345. Reverse Vowels of a String
按 -> 键看下一题!
347. Top K Frequent Elements