leetcode之Range Sum Query 2D - Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
这里写图片描述
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
题目描述:该题是Range Sum Query - Immutable的延伸,做法类似,设
value[i][j]表示(i,j)到右下角的矩形框内所有元素的和,那么可以得到如下递推关系:
value[i][j]=value[i+1][j]+value[i][j+1]-value[i+1][j+1] + matrix[i][j]
为了防止角标越界,value的维度为(row+1)*(col+1)
那么:
sumRegion(row1,col1,row2,col2) = value[row1][col1] - value[row2+1][col1] - value[row1][col2+1] + value[row2+1][col2+1]
此时的时间复杂度为O(row*col),查找的时间复杂度为O(1)
具体代码如下:

class NumMatrix {
private:
    int **value;
public:
    NumMatrix(vector<vector<int>> &matrix) {
        int row = matrix.size();
        int col = row ? matrix[0].size() : 0;
        value = new int*[row + 1];
        for(int i = 0; i <= row; ++i){
            value[i] = new int[col+1];
            memset(value[i],0,col+1);
        }
        for(int i = row - 1; i >= 0; --i){
            for(int j = col - 1; j >= 0; --j){
                value[i][j] = value[i+1][j] + value[i][j+1] - value[i+1][j+1] + matrix[i][j];
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        return value[row1][col1] - value[row2+1][col1] - value[row1][col2+1] + value[row2+1][col2+1];
    }
};


// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);

你可能感兴趣的:(leetcode)