642. 数据流滑动窗口平均值

642. 数据流滑动窗口平均值

中文English

给出一串整数流和窗口大小,计算滑动窗口中所有整数的平均值。

样例

样例1 :

MovingAverage m = new MovingAverage(3);
m.next(1) = 1 // 返回 1.00000
m.next(10) = (1 + 10) / 2 // 返回 5.50000
m.next(3) = (1 + 10 + 3) / 3 // 返回 4.66667
m.next(5) = (10 + 3 + 5) / 3 // 返回 6.00000
class MovingAverage:
    """
    @param: size: An integer
    """
    def __init__(self, size):
        # do intialization if necessary
        self.queue = []
        self.size = size 
        self.sum = 0

    """
    @param: val: An integer
    @return:  
    """
    def next(self, val):
        # write your code here
        if (len(self.queue) < self.size):
            self.queue.append(val)
            self.sum += val 
        else:
            if len(self.queue) == self.size:
                self.queue.append(val)
                pop_num = self.queue.pop(0)
                self.sum = self.sum + val - pop_num
        
        return self.sum / len(self.queue)


# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param = obj.next(val)
第二个版本(滚动数组写法)
class MovingAverage:
    """
    @param: size: An integer
    """
    def __init__(self, size):
        # do intialization if necessary
        self.size = size
        self.count = 0 
        self.queue = [0]*size
        self.sum = 0

    """
    @param: val: An integer
    @return:  
    """
    def next(self, val):
        # write your code here
        index = self.count % self.size 
        self.sum = self.sum + val - self.queue[index]
        self.queue[index] = val
        self.count += 1 
        
        return self.sum / self.count if self.count < self.size else self.sum / self.size

# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param = obj.next(val)
 
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13216371.html