*281. Zigzag Iterator

https://leetcode.com/problems/zigzag-iterator/

solution

class ZigzagIterator:
    def __init__(self, v1: List[int], v2: List[int]):
        self.current = 0
        self.size = 2
        self.indices = [0] * self.size
        self.vectors = [v1, v2]

    def next(self) -> int:
        vector = self.vectors[self.current]
        index = self.indices[self.current]
        result = vector[index]
        self.indices[self.current] = index + 1
        self.current = (self.current + 1) % self.size
        return result

    def hasNext(self) -> bool:
        start = self.current
        while self.indices[self.current] == len(self.vectors[self.current]):
            self.current = (self.current + 1) % self.size
            if self.current == start:
                return False
        return True

时间复杂度:O() 空间复杂度:O()

Last updated