Clean python solution with comments


  • 0
    H
    class Vector2D(object):
    
        def __init__(self, vec2d):
            """
            Initialize your data structure here.
            :type vec2d: List[List[int]]
            """
            self._data = vec2d if vec2d else [[]]
            x, y = 0, 0
            # skip all None vectors
            while x < len(self._data) and not self._data[x]:
                x += 1
            self._cur_ptr = (x, y)
            
    
        def next(self):
            """
            :rtype: int
            """
            x, y = self._cur_ptr
            ret = self._data[x][y]
            if y < len(self._data[x]) - 1:
                y += 1
            else:
                x += 1
                # skip all None vectors
                while x < len(self._data) and not self._data[x]:
                    x += 1
                y = 0
            self._cur_ptr = (x, y)
            return ret
            
    
        def hasNext(self):
            """
            :rtype: bool
            """
            x, y = self._cur_ptr
            return (x < len(self._data) - 1) or \
        			(x == len(self._data) - 1 and y <= len(self._data[x]) - 1)
    

Log in to reply
 

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