C# Linq Queue Average


  • 1
    C

    public class MovingAverage {

    Queue<int> Window { get; set; }
    int WindowSize { get; set;}
    
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.Window = new Queue<int>();
        this.WindowSize = size;
    }
    
    public double Next(int val) {
        if (Window.Count() >= this.WindowSize)
        {
            Window.Dequeue();
        }
        
        Window.Enqueue(val);
        return Window.Average(a => a);
    }
    

    }


  • 0

    Good usage on LINQ. I added my code if it's asking for optimization/LINQ is not allowed to use.
    From 400ish ms to 200ish ms

    public class MovingAverage {
    
        /** Initialize your data structure here. */
        private Queue<int> Window { get; set; }
        private int WinSize { get; set; }
        private int sum   { get; set; }
        
        public MovingAverage(int size) {
            Window = new Queue<int>();
            WinSize = size;
        }
        
        public double Next(int val) {
            if(Window.Count >= WinSize)
               sum -= Window.Dequeue();
            Window.Enqueue(val);
            sum += val;
            
            return (double)sum/Window.Count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.