Simple solution with an array - fast hasNext and next


  • 0
    L

    Initializing the Vector2D might be less performant but that is a one time operation hasNext and next perform way faster than any other solution I found.

    public class Vector2D implements Iterator<Integer> {
        Integer[] values = null;
        int curser = 0;
        public Vector2D(List<List<Integer>> vec2d) {
            int size = 0;
            for(List each: vec2d) {
                size+=each.size();
            }
            values = new Integer[size];
            for(List<Integer> each: vec2d) {
                for(Integer value : each) {
                    values[curser++] = value;
                }
            }
            curser = 0;
        }
    
        @Override
        public Integer next() {
            return values[curser++];
        }
    
        @Override
        public boolean hasNext() {
            return curser < values.length;
        }
    }
    

Log in to reply
 

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