python solution


  • 0
    A
    def __init__(self, size):
        """
        Initialize your data structure here.
        :type size: int
        """
        self.size = size
        self.a = []
        
    def next(self, val):
        """
        :type val: int
        :rtype: float
        """
        if len(self.a) == self.size:
            self.a = self.a[1:]
        self.a += [val]
        return sum(self.a)/float(len(self.a))

  • 0

    self.a = self.a[1:] takes O(n). You can use deque to achieve O(1).


  • 0
    A

    @Helly0000
    Yeah, deque is better for this problem. Thanks for your suggestion !
    Since there are already some deque solutions, I will leave my solution as it is.


Log in to reply
 

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