Simple Java solution for K-vector using two pointers


  • 0
    A
    public class ZigzagIterator {
        private int externalIndex = 0;
        private int interIndex = 0;
        private int maxLen = 0;
        private List<List<Integer>> lists;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            lists = new ArrayList<>();
            if (v1 != null && v1.size() != 0) {
                lists.add(v1);
                maxLen = Math.max(v1.size(), maxLen);
            }
            
            if (v2 != null && v2.size() != 0) {
                lists.add(v2);
                maxLen = Math.max(v2.size(), maxLen);
            }
        }
    
        public int next() {
            int result = lists.get(externalIndex).get(interIndex);
            externalIndex ++;
            return result;
        }
    
        public boolean hasNext() {
           if (externalIndex >= lists.size()) {
               externalIndex = 0;
               interIndex ++;
               if (interIndex >= maxLen) return false;
           }
           while(externalIndex < lists.size() && lists.get(externalIndex).size() <= interIndex) {
               externalIndex ++;
           }
           if (externalIndex >= lists.size()) return hasNext();
           else return true;
        }
    }
    
    /**
     * Your ZigzagIterator object will be instantiated and called as such:
     * ZigzagIterator i = new ZigzagIterator(v1, v2);
     * while (i.hasNext()) v[f()] = i.next();
     */
    

Log in to reply
 

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