C++ implementation using vector iterators only.


  • 0
    A
    class Vector2D {
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            rowIter = vec2d.begin();
            rowEnd = vec2d.end();
            if (rowIter != rowEnd) {
                colIter = rowIter->begin();
                colEnd = rowIter->end();
            }
        }
    
        int next() {
            return *colIter++;
        }
    
        bool hasNext() {
            while (colIter == colEnd && rowIter != rowEnd) {
                ++rowIter;
                colIter = rowIter->begin();
                colEnd = rowIter->end();
            }
    
            if (rowIter == rowEnd)
                return false;
            
            return true;
        }
    
    private:
        vector<vector<int>>::iterator rowIter;
        vector<vector<int>>::iterator rowEnd;
        vector<int>::iterator colIter;
        vector<int>::iterator colEnd;
    };

Log in to reply
 

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