Java solution using queue for k-vector


  • 0
    M

    Similar to the solution given by @kevinhsu with a small modification in next() function. Added a check that avoids removing and adding an Iterator from the queue if it has just one element.

    public class ZigzagIterator {
    
        Queue<Iterator<Integer>> queue;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            queue = new LinkedList<Iterator<Integer>>();
            if(!v1.isEmpty()) queue.offer(v1.iterator());
            if(!v2.isEmpty()) queue.offer(v2.iterator());
        }
    
        public int next() {
             
            Iterator<Integer> c = queue.peek();
            int i = c.next();
            if(queue.size()>1 || !c.hasNext()) {
                queue.poll();
                if(c.hasNext()) queue.offer(c);
            }
            return i;
        }
    
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    }
    

Log in to reply
 

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