Java Solution O(1) space O(1) time with iterator


  • 0
    Y
    public class Vector2D implements Iterator<Integer> {
    
        ListIterator<List<Integer>> rowIter;
        ListIterator<Integer> colIter;
        
        public Vector2D(List<List<Integer>> vec2d) {
            rowIter = vec2d.listIterator();
        }
    
        @Override
        public Integer next() {
            return colIter.next();
        }
    
        @Override
        public boolean hasNext() {
            while (colIter == null || !colIter.hasNext()) {
                if (!rowIter.hasNext()) {
                    return false;
                }
                colIter = rowIter.next().listIterator();
            }
            return true;
        }
    }
    
    /**
     * Your Vector2D object will be instantiated and called as such:
     * Vector2D i = new Vector2D(vec2d);
     * 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.