My Python Solution


  • 7
    Y
    class Vector2D:
        # Initialize your data structure here.
        # @param {integer[][]} vec2d
        def __init__(self, vec2d):
            self.col = 0
            self.row = 0
            self.vec = vec2d
            
        # @return {integer}
        def next(self):
            result = self.vec[self.row][self.col]
            self.col += 1
            return result
    
        # @return {boolean}
        def hasNext(self):
            while self.row < len(self.vec):
                if self.col < len(self.vec[self.row]):
                    return True
                
                self.col = 0
                self.row += 1
                
            return False

  • 0
    L

    better to use iter in python:

    class Vector2D(object):
    
        def __init__(self, vec2d):
            """
            Initialize your data structure here.
            :type vec2d: List[List[int]]
            """
            def get():
                for arr in vec2d:
                    for item in arr:
                        yield item
            self.own_iter = iter(get())
            self.latest = next(self.own_iter, None)
            
    
        def next(self):
            """
            :rtype: int
            """
            if self.hasNext():
                t = self.latest
                self.latest = next(self.own_iter, None)
                return t
            
    
        def hasNext(self):
            """
            :rtype: bool
            """
            return self.latest != None

  • 0
    J

    @LeoShi What's the advantage of this solution?


Log in to reply
 

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