Short Python With Detailed Explaination


  • 0
    W

    init: x and y are two variables to keep track of the index of current element.

    next: next does nothing but naively return the current value at index (x, y). It increments y by 1 to get to the next possible index. This index might is guaranteed to be valid because it was updated in the hasNext function prior to calling this function.

    hasNext: It updates index (x, y) and loops internally until a valid index position or out of bound.

    '''
    class Vector2D(object):

    def __init__(self, vec2d):
        """
        Initialize your data structure here.
        :type vec2d: List[List[int]]
        """
        self.vec = vec2d
        self.x = self.y = 0
    
    def next(self):
        """
        :rtype: int
        """
        self.y+=1
        return self.vec[self.x][self.y-1]
    
    
    def hasNext(self):
        """
        :rtype: bool
        """
        if self.x < len(self.vec) and self.y < len(self.vec[self.x]):
            return True
        while (self.x < len(self.vec)):
            if self.x + 1 >= len(self.vec):
                return False
            elif self.vec[self.x + 1] == []:
                self.x += 1
            else:
                self.x += 1
                self.y = 0
                return True
    

    '''


Log in to reply
 

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