[java/4ms] solution for k vectors, cyclic token.


  • 0
    D
    public class ZigzagIterator {
        int token;
        int[] pos = new int[2];
        List<Integer>[] zigzag = new ArrayList[2];
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            zigzag[0] = v1;
            zigzag[1] = v2;
        }
    
        public int next() {
            int guard = 0;
            while (true) {
                token &= 1;
                if (pos[token] < zigzag[token].size()) {
                    return zigzag[token].get(pos[token++]++);
                }
                ++token;
                // if user call without using hasNext first
                if (++guard == 2) return -1;
            } 
        }
    
        public boolean hasNext() {
            return pos[0] < zigzag[0].size() || pos[1] < zigzag[1].size();
        }
    }
    

Log in to reply
 

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