Sharing my 20ms C++ solution


  • 0
    T
    class Vector2D {
    private:
        vector<vector<int>> matrix;
        int x;
        int y;
        
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            matrix = vec2d;
            x = 0;
            y = 0;
        }
    
        int next() {
            y++;
            return matrix[x][y-1];
        }
    
        bool hasNext() {
            if(x>=matrix.size())
                return false;
            while(y>=matrix[x].size())
            {
                y = 0;
                x++;
                if(x>=matrix.size())
                    return false;
            }
            
            return true;
        }
    };
    
    /**
     * Your Vector2D object will be instantiated and called as such:
     * Vector2D i(vec2d);
     * while (i.hasNext()) cout << i.next();
     */

Log in to reply
 

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