Short and easy Java solution with two iterators


  • 0
    N
    Iterator<List<Integer>> i;
    Iterator<Integer> j;
    
    public Vector2D(List<List<Integer>> vec2d) {
        i = (vec2d != null) ? vec2d.iterator() : Collections.emptyIterator();
        j = i.hasNext() ? i.next().iterator() : Collections.emptyIterator();
    }
    
    public int next() {
        return j.next();
    }
    
    public boolean hasNext() {
        while (! j.hasNext()) {
            if (! i.hasNext()) return false;
            j = i.next().iterator();
        }
        return true;
    }

Log in to reply
 

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