Java O(1) space solution


  • 0
    S
    public class Vector2D {
        private int row = -1, column = -1;
        private List<List<Integer>> list;
        private boolean updated = false, hasNext = false;
    
        public Vector2D(List<List<Integer>> vec2d) {
            list = vec2d;
        }
    
        public int next() {
            if(!updated) hasNext();
            int r = list.get(row).get(column);
            updated = false;
            column ++;
            return r;
        }
    
        public boolean hasNext() {
            if(updated) return hasNext;
            while(row < 0 || (row < list.size() && column >= list.get(row).size())){
                row++;
                column = 0;
            } 
            if(row >= list.size()) hasNext = false;
            else hasNext = true;
            updated = true;
            return hasNext;
        }
    }

  • 1
    S

    I think this is a better solution since the point of this question is to design iterator. If Iterator provided by Java is used, the problem is pointless.


Log in to reply
 

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