C++ Simple Solution, Concise Code


  • 1
    class NumMatrix {
    public:
        vector<vector<int>> board;
    
        NumMatrix(vector<vector<int>> &matrix) {
            board = matrix;
            int m = board.size(), n = m ? board[0].size() : 0;
            for (int i = 0; i < m; i++) 
                for (int j = 1; j < n; j++)
                    board[i][j] += board[i][j - 1];
        }
    
        void update(int row, int col, int val) {
            int cpt = val - board[row][col] + (col > 0 ? board[row][col - 1] : 0);
            for (int i = col; i < board[0].size(); i++)
                board[row][i] += cpt;
        }
    
        int sumRegion(int row1, int col1, int row2, int col2) {
            int res = 0;
            for (int i = row1; i <= row2; i++)
                res += board[i][col2] - (col1 > 0 ? board[i][col1 - 1] : 0);
            return res;
        }
    };
    

  • 0
    M

    Your solution is the best!


Log in to reply
 

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