Short and generic Python solution


  • 0
    class ZigzagIterator(object):
    
        def __init__(self, *vecs):
            self.vecs, self.n = [v for v in vecs], sum(len(v) for v in vecs)
            self.idxs = [x for x in range(len(self.vecs)) if len(self.vecs[x])]
            self.r = self.c = self.i = 0
            
        
        def next(self):
            val = self.vecs[self.idxs[self.r]][self.c]
            self.r += 1
            self.i += 1
            return val
            
        
        def hasNext(self):
            if self.i < self.n:
                if self.r >= len(self.idxs):
                    self.c += 1
                    self.r = 0
                    self.idxs = [e 
                                for e in self.idxs 
                                if self.c < len(self.vecs[e])]
                return True
            return False

Log in to reply
 

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