Two solutions using iterator and queue


  • 0
    H
    //Solution using iterator
    public class Vector2D implements Iterator<Integer> {
        private Iterator<List<Integer>> listIter;
        private Iterator<Integer> iter;
        public Vector2D(List<List<Integer>> vec2d) {
            listIter = vec2d.iterator();
        }
    
        @Override
        public Integer next() {
            return iter.next();
        }
    
        @Override
        public boolean hasNext() {
            if (iter == null || !iter.hasNext()) {
                 while (listIter.hasNext()) {
                    iter = listIter.next().iterator();
                    if (iter.hasNext()) return true;
                }
                return false;
            } 
            return true;
        }
    }
    

    //Solution using queue
    public class Vector2D implements Iterator<Integer> {
        Queue<Iterator<Integer>> queue;
    
        public Vector2D(List<List<Integer>> vec2d) {
            queue = new LinkedList<>();
            for (List<Integer> list : vec2d) {
                if (!list.isEmpty())
                    queue.offer(list.iterator());
            }
        }
    
        @Override
        public Integer next() {
            Iterator<Integer> iterator = queue.peek();
            int res = iterator.next();
            if (!iterator.hasNext()) queue.poll();
            return res;
        }
    
        @Override
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    }
    

Log in to reply
 

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