304. Range Sum Query 2D - Immutable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class NumMatrix {

private final int[][] sumMatrix; // 从左上角至当前节点形成矩形的和

public NumMatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
this.sumMatrix = new int[m + 1][n + 1]; // 多申请一个是避免处理索引越界的情况

for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
this.sumMatrix[i][j] = this.sumMatrix[i - 1][j] + this.sumMatrix[i][j - 1] - this.sumMatrix[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}

public int sumRegion(int row1, int col1, int row2, int col2) {
// 对齐为 sumMatrix 中的下标
row1++;
col1++;
row2++;
col2++;

return sumMatrix[row2][col2] - sumMatrix[row2][col1 - 1] - sumMatrix[row1 - 1][col2] + sumMatrix[row1 - 1][col1 - 1];
}

}

References

304. Range Sum Query 2D - Immutable
剑指 Offer II 013. 二维子矩阵的和