C++ 14ms using only iterators with O(1) space


  • 0
    B
    class Vector2D {
        vector<vector<int>>* matrix;
        vector<vector<int>>::iterator y;
        vector<int>::iterator x;
        
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            matrix = &vec2d;
            y = matrix->begin();
            if(y!=matrix->end()) x=y->begin();
        }
    
        int next() {
            return *x++;
        }
    
        bool hasNext() {
            while(y!=matrix->end() && x==y->end()) // change line
            {
                y++;
                x=y->begin();
            }
            return y!=matrix->end();
    
        }
    };
    

Log in to reply
 

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