Java solution


  • 0
    J
        List<List<Integer>> vec2d;
        Iterator<Integer> curIterator;
        int curIndex;
    
        public Vector2D(List<List<Integer>> vec2d) {
            this.vec2d = vec2d;
            curIndex = getNextNonEmptyVector(vec2d, -1);
            curIterator = curIndex >= 0 ? vec2d.get(curIndex).iterator() : null;
        }
        
        private static int getNextNonEmptyVector(List<List<Integer>> vec2d, int curIndex) {
            for (int i = curIndex + 1; i < vec2d.size(); i++) if (vec2d.get(i).size() > 0) return i;
            return -1;
        }
    
        @Override
        public Integer next() {
            if (curIterator != null) {
                Integer v = curIterator.next();
                if (!curIterator.hasNext()) {
                    curIndex = getNextNonEmptyVector(vec2d, curIndex);
                    curIterator = curIndex >= 0 ? vec2d.get(curIndex).iterator() : null;
                }
                return v;
            }
            return null;
        }
    
        @Override
        public boolean hasNext() {
            return curIterator != null && curIterator.hasNext();
        }
    

Log in to reply
 

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