这题做法其实就很简单了。如果说我们有一个辅助二维数组f(n, n),其中任意f(i, j)是从matrix(0, 0)到matrix(i, j)的矩阵的和
那么这一题subRegion(row1, col1, row2, col2)其实就是f(row2, col2)这个矩阵,减去f(row1, col2)这个矩阵,再减去f(row2, col1)这个矩阵,最后加上f(row1, col1)这个被重复减去了两次的矩阵就可以了。注意一下row1 = 0 或者 col1 = 0的edge case就可以了。
根据上面描述,给出代码如下:
private int[][] _calculated;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return;
this._calculated = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
int curRowSum = 0;
for (int j = 0; j < matrix[i].length; j++) {
curRowSum += matrix[i][j];
this._calculated[i][j] = curRowSum;
if (i > 0) this._calculated[i][j] += this._calculated[i - 1][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int rightTop = this._calculated[row2][col2];
int rightBot = row1 > 0 ? this._calculated[row1 - 1][col2] : 0;
int leftTop = col1 > 0 ? this._calculated[row2][col1 - 1] : 0;
int leftBot = row1 > 0 && col1 > 0 ? this._calculated[row1 - 1][col1 - 1] : 0;
return rightTop - leftTop - rightBot + leftBot;
}