Python solution with detailed explanation


  • 0
    G

    Solution

    Flatten 2D Vector https://leetcode.com/problems/flatten-2d-vector/?tab=Description

    1. Invariant: We will maintain the next correct index for x,y before the next call
    2. hasNext is called before we call next
    3. Remember we can have empty rows
    4. At next, we extract x = vec2d[x,y]. If y+1 is less than the length of the current row, then set y to y+1. Otherwise increment x to next row. Make sure you adjust for empty rows at this point (and at initialization).
    5. hasNext just needs to check valid row number.
    class Vector2D(object):
        def skip_empty_rows_x(self):
            while self.x < len(self.vec2d) and len(self.vec2d[self.x]) == 0:
                self.x = self.x + 1
            return
    
        def __init__(self, vec2d):
            """
            Initialize your data structure here.
            :type vec2d: List[List[int]]
            """
            self.vec2d = vec2d
            self.x, self.y = 0, 0
            self.skip_empty_rows_x()
    
        def next(self):
            """
            :rtype: int
            """
            x = self.vec2d[self.x][self.y]
            self.y = self.y+1
            if self.y == len(self.vec2d[self.x]):
                self.x, self.y = self.x+1, 0
                self.skip_empty_rows_x()
            return x
    
        def hasNext(self):
            """
            :rtype: bool
            """
            if self.x >= len(self.vec2d):
                return False
            return True
    

Log in to reply
 

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