Java 3ms Iterator Solution


  • 0

    similar as other iterator questions in Leetcode, maybe not as concise as others' post, but I found this template can be applied to other questions.

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

Log in to reply
 

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