Moving Average from Data Stream
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 200 ms)β
| Metric | Value |
|---|---|
| Runtime | 200 ms |
| Memory | 32.7 MB |
| Date | 2019-12-16 |
Solution
public class MovingAverage {
public Queue<int> stream;
private double currentSum = 0.0;
private int Size;
/** Initialize your data structure here. */
public MovingAverage(int size)
{
stream = new Queue<int>();
Size = size;
}
public double Next(int val)
{
if(Size==stream.Count)
{
var front = stream.Dequeue();
stream.Enqueue(val);
currentSum = currentSum-front+val;
return currentSum/(double)Size;
}
currentSum+=val;
stream.Enqueue(val);
return currentSum/stream.Count;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.Next(val);
*/
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |