Simple Java O(1) solution


  • 0
    S

    Assign crr to itr1 or itr2 initially. Pick from crr and assign crr to other if other has more items.

    public class ZigzagIterator {
        Iterator<Integer> itr1, itr2, crr;
        
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            itr1 = v1.iterator();
            itr2 = v2.iterator();
            crr = itr1.hasNext() ? itr1 : itr2;
        }
    
        public int next() {
            int res = crr.next();
            Iterator<Integer> other = itr1 == crr ? itr2 : itr1;
            if (other.hasNext()) crr = other;
            return res;
        }
    
        public boolean hasNext() {
            return crr.hasNext();
        }
    }
    

Log in to reply
 

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