C# O(1)


  • 0
    G

    C# Real O(1)

    //346. Moving Average from Data Stream
    
    public class MovingAverage {
    
        
    	public int OldestElementPosition;
        public int HistoryCount;
    	public int mSize;
    	public double LastSum;
    	public int LastVal;
        public int[] Moving;
    
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            OldestElementPosition = 0;
    		HistoryCount = 0;
    		mSize = size;
    		LastSum = 0;
    		if(mSize > 0) 
    		{
    			Moving = new int[mSize];
    		}
    		else
    		{
    			Moving = null;
    		}			
        }
    	
        public double Next(int val) {
    		double result = 0;
    		double sum = 0;
    		
    		if(HistoryCount < mSize )
    		{
    			sum = LastSum + val;
    			Moving[HistoryCount] = val;			
    			HistoryCount++;	
    			result = sum / HistoryCount;					
    		}
    		else
    		{
    			sum = LastSum - Moving[OldestElementPosition] + val;
    			result = sum / mSize;
    			Moving[OldestElementPosition] = val;
    			HistoryCount++;	
    			
    			OldestElementPosition = (OldestElementPosition == (mSize - 1)) ? 0 : (OldestElementPosition + 1);
    		}		
    		
    		LastSum = sum;
    		
    		return result;
        }
    }
    
    /**
     * Your MovingAverage object will be instantiated and called as such:
     * MovingAverage obj = new MovingAverage(size);
     * double param_1 = obj.Next(val);
     */
    

Log in to reply
 

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