Simple Python Solution (O(n) time, O(k) space that eventually reduces with each call)


  • 0
    L

    from collections import deque
    class ZigzagIterator(object):

    def __init__(self, v1, v2):
        """
        Initialize your data structure here.
        :type v1: List[int]
        :type v2: List[int]
        """
        self.final=deque()
        i=0
        while i<len(v1) and i<len(v2):
            self.final.append(v1[i])
            self.final.append(v2[i])
            i+=1
    
        while i<len(v1):
            self.final.append(v1[i])
            i+=1
        while i<len(v2):
            self.final.append(v2[i])
            i+=1
    def next(self):
        """
        :rtype: int
        """
        return self.final.popleft()
    
    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.final)!=0

Log in to reply
 

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