Neat solution in Java only using iterators


  • 0
    public class Vector2D implements Iterator<Integer> {
    
        private Iterator<List<Integer>> listIterator;
        private Iterator<Integer> integerIterator;
    
        public Vector2D(List<List<Integer>> vec2d) {
            listIterator = vec2d.iterator();
            if (listIterator.hasNext()) {
                integerIterator = listIterator.next().iterator();
            }
        }
    
        @Override
        public boolean hasNext() {
            if (integerIterator != null && integerIterator.hasNext()) return true;
            while (listIterator.hasNext()) {
                integerIterator = listIterator.next().iterator();
                if (integerIterator.hasNext()) {
                    return true;
                }
            }
            return false;
        }
    
        @Override
        public Integer next() {
            return integerIterator.next();
        }
    }
    

Log in to reply
 

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