题目链接:
力扣https://leetcode-cn.com/problems/range-sum-query-2d-immutable/
【分析】这是一个二维数组的前缀和问题,先对每行求前缀和,再对每列求前缀和,用右下角减去上面左面再加左上角即可。
class NumMatrix {
int m, n;
int[][] pre;
public NumMatrix(int[][] matrix) {
m = matrix.length;
n = matrix[0].length;
pre = new int[m][n];
int i, j;
for(i = 0; i < m; i++){
pre[i][0] = matrix[i][0];
}
for(i = 0; i < m; i++){
for(j = 1; j < n; j++){
pre[i][j] = pre[i][j - 1] + matrix[i][j];
}
}
for(j = 0; j < n; j++){
for(i = 1; i < m; i++){
pre[i][j] += pre[i - 1][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = pre[row2][col2], t1 = 0, t2 = 0, t3 = 0;
int x1 = row1 - 1, y1 = col2;
if(x1 >= 0) t1 = pre[x1][y1];
int x2 = row2, y2 = col1 - 1;
if(y2 >= 0) t2 = pre[x2][y2];
int x3 = row1 - 1, y3 = col1 - 1;
if(x3 >= 0 && y3 >= 0) t3 = pre[x3][y3];
return sum - t1 - t2 + t3;
}
}