Skip to main content

Moving Average from Data Stream

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 200 ms)​

MetricValue
Runtime200 ms
Memory32.7 MB
Date2019-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​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed