20ms C++ O(1) space linear time solution


  • 0

    Maintain two indices m(row), n(column) to indicate the position so far, and a number remain to tell if there is actually any number left for printing.

    class Vector2D {
    private:
        vector<vector<int>> _vec2d;
        int m=0;
        int n=0;
        int remain;
    
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            _vec2d=vec2d;
            for(auto i: _vec2d) remain+=i.size();       
        }
    
        int next() {
            int val=_vec2d[m][n];
            if(n==_vec2d[m].size()-1){ //don’t miss out “-1”
                n=0;
                m++; 
            }else{n++;} //new line
            remain--;
            return val;
        }
    
        bool hasNext() {
            if(_vec2d.size()==0 || remain==0) return false;
            while(_vec2d[m].size()==0) m++; //skip empty vectors
            return true;
        }
    };

  • 0
    B
    This post is deleted!

Log in to reply
 

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