C++ Solution 56ms using a 2D vector


  • 0
    W
    vector<vector<int>> rowsum;
    int rowc = 0;
    int colc = 0;
    NumMatrix(vector<vector<int>> &matrix) {
        if(!matrix.size() || !matrix[0].size()) return;
        int m = matrix.size(), n = matrix[0].size();
        rowc = m;
        colc = n;
        rowsum.resize(m,vector<int>(n,0));
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                rowsum[i][j] = (j<1 ? 0:rowsum[i][j-1]) + matrix[i][j];
            }
        }
    }
    
    void update(int row, int col, int val) {
        if(row<0||row>=rowc||col<0||col>=colc) return;
        int prev = rowsum[row][col] - (col > 0 ? rowsum[row][col-1] : 0);
        for(int i=col;i<colc;i++)
            rowsum[row][i] = rowsum[row][i] + val - prev;
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        int res = 0;
        if(row1 < 0 || col1 < 0 || row2 >= rowc || col2 >= colc) return res;
        for(int i=row1;i<=row2;i++)
            res += rowsum[i][col2] - (col1 >= 1 ? rowsum[i][col1-1]:0);
        
        return res;
    }

Log in to reply
 

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