Share my simple Java code using only Java built-in iterators(demanded in the follow-up) and beats 94.59% run times


  • 0
    M
    public class Vector2D {
    
        private Iterator<List<Integer>> rowIterator;
        private Iterator<Integer> colIterator;
    
        public Vector2D(List<List<Integer>> vec2d) {
            rowIterator = vec2d.iterator();
            if (rowIterator.hasNext()) { 
                colIterator = rowIterator.next().iterator();
                moveToNextAvailable();
            }
        }
    
        public int next() {
            Integer save = colIterator.next();
            moveToNextAvailable();
            return (int) save;
        }
    
        public boolean hasNext() {
            return colIterator!=null && colIterator.hasNext();
        }
        
        private void moveToNextAvailable() {
            while (!colIterator.hasNext() && rowIterator.hasNext()) {
                colIterator = rowIterator.next().iterator();
            }
        }
    }

  • 0

    You solution cannot have remove().


Log in to reply
 

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