Golang concise solution using array


  • 0

    We don't need to use deque to manage the earliest inserted element.
    If we count a number of insertion like count as 0, 1, 2, ...
    Then always count % size is an index we want to pop out from the stream, then we can replace that index's value.

    type MovingAverage struct {
    	Queue  []int
    	Count  int
    	Size   int
    	CurSum int
    }
    
    /** Initialize your data structure here. */
    func Constructor(size int) MovingAverage {
    	ma := MovingAverage{
    		Size:   size,
    		CurSum: 0,
    		Count:  0,
    	}
    	ma.Queue = make([]int, size)
    	return ma
    }
    
    func (this *MovingAverage) Next(val int) float64 {
    	if this.Count < this.Size {
    		this.CurSum = this.CurSum + val
    		this.Queue[this.Count] = val
    		this.Count += 1
    		return float64(this.CurSum) / float64(this.Count)
    	}
    
    	i := this.Count % this.Size
    	this.CurSum = this.CurSum - this.Queue[i] + val
    	this.Queue[i] = val
    	this.Count += 1
    	return float64(this.CurSum) / float64(this.Size)
    }
    
    

Log in to reply
 

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