Two approaches: Queue and iterators only


  • 0
    A

    Using Queue :

    public class Vector2D implements Iterator<Integer> {
    
        private Queue<Iterator<Integer>> iterators;
    
        public Vector2D(List<List<Integer>> vector2d) {
            iterators = new LinkedList<>();
            vector2d.forEach(vector -> {
                if (!vector.isEmpty()) {
                    iterators.offer(vector.iterator());
                }
            });
        }
    
        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Empty iterator");
            }
    
            Iterator<Integer> current = iterators.peek();
            int result = current.next();
            if (!current.hasNext()) {
                iterators.poll();
            }
    
            return result;
        }
    
        @Override
        public boolean hasNext() {
            return !iterators.isEmpty();
        }
    }
    

    Using iterators only :

    public class Vector2D implements Iterator<Integer> {
        
        private final Iterator<Iterator<Integer>> nestedIterators;
        private Iterator<Integer> current;
    
        public Vector2D(final List<List<Integer>> vector2d) {
            List<Iterator<Integer>> iterators = new ArrayList<>();
            vector2d.forEach(vector -> {
                if (!vector.isEmpty()) {
                    iterators.add(vector.iterator());
                }
            });
            nestedIterators = iterators.iterator();
            current = null;
        }
    
        @Override
        public boolean hasNext() {
            return nestedIterators.hasNext() || current != null;
        }
    
        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Empty iterator");
            }
    
            if (current == null) {
                current = nestedIterators.next();
            }
    
            int result = current.next();
            if (!current.hasNext()) {
                current = null;
            }
    
            return result;
        }
    }
    

Log in to reply
 

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