Clear Java solution, K way scalable


  • 0

    Use a Queue to store all the iterators. Space complexity O(k).

    public class ZigzagIterator {
        Queue<Iterator<Integer>> q = new ArrayDeque<>();
            
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            if (v1 != null && v1.size() != 0) q.add(v1.iterator());
            if (v2 != null && v2.size() != 0) q.add(v2.iterator());
        }
    
        public int next() {
            Iterator<Integer> it = q.poll();
            int res = it.next();
            if (it.hasNext()) q.add(it);
            return res;
        }
    
        public boolean hasNext() {
            return !q.isEmpty();
        }
    }
    

Log in to reply
 

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