Simple Java code with 2 iterators. 3 ms.


  • 0
    S

    I didn't realize my idea is quite similar to @mlblount45 . But I didn't put any helper function. Code is simple and clear:

    public class Vector2D implements Iterator<Integer> {
    
    	Iterator<List<Integer>> iter;
    	Iterator<Integer> nestIter;
        public Vector2D(List<List<Integer>> vec2d) {
            if(vec2d == null || vec2d.size() == 0) return;
            iter = vec2d.iterator();
            if(iter.hasNext()) nestIter = iter.next().iterator();
        }
    
        @Override
        public Integer next() {
        	return nestIter.next();
        }
    
        @Override
        public boolean hasNext() {
            if(nestIter == null) return false;
    		while(!nestIter.hasNext() && iter.hasNext()) nestIter = iter.next().iterator();
    		return nestIter.hasNext();
        }
    }
    

Log in to reply
 

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