Transparent C++ solution - O(1) space, O(N) time on-demand only


  • 0
    X
    class Vector2D {
        const vector<vector<int>>& data;
        size_t row;
        size_t col;
        bool isAtEnd;
    public:
        Vector2D(vector<vector<int>>& vec2d) : data(vec2d), row(0), col(0), isAtEnd(true) {
            while(row < data.size()) {
                if(data[row].empty()) ++row;
                else {
                    isAtEnd = false;
                    break;
                }
            }
        }
    
        int next() {
            auto result = data[row][col];
            if(col + 1 < data[row].size()) ++col;
            else {
                ++row;
                while(row < data.size()) {
                    if(data[row].empty()) ++row;
                    else {
                        col = 0;
                        break;
                    }
                }
                if(row == data.size()) isAtEnd = true;
            }
            return result;
        }
    
        bool hasNext() {
            return !isAtEnd;
        }
    };

Log in to reply
 

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