Java simple solution easily extends to k vector


  • 1
    S

    In next() function, remove the first List<Integer>, get value and add to the end of List<List<Integer>> if not empty. Can ensure the zigzag order even for k vectors.

    public class ZigzagIterator {
        List<List<Integer>> list;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            list = new ArrayList<>();
            if(v1.size()>0) list.add(v1);
            if(v2.size()>0) list.add(v2);
        }
    
        public int next() {
            if(!hasNext()) return -1;
            List<Integer> cur = list.remove(0);
            int val = cur.remove(0);
            if(cur.size()>0) list.add(cur);
            return val;
        }
    
        public boolean hasNext() {
            return list.size()>0;
        }
    }
    

    Improve by using Iterator.

    public class ZigzagIterator {
        List<Iterator<Integer>> it ;
        
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            it = new ArrayList<>();
            if(v1.size()>0)
                it.add(v1.iterator());
            if(v2.size()>0)
                it.add(v2.iterator());
        }
    
        public int next() {
            if(!hasNext()) return -1;
            Iterator<Integer> i = it.remove(0);
            int val = i.next();
            if(i.hasNext()) it.add(i);
            return val;
        }
    
        public boolean hasNext() {
            return it.size()>0;
        }
    }

  • 0

    How does this easily extend to k vectors? You're cycling, not zigzagging.


Log in to reply
 

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