Skip to content

Commit 1e5d3ea

Browse files
Merge pull request neetcode-gh#3164 from KaiyangYao/main
Create: 0304-range-sum-query-2d-immutable.java
2 parents 09cbb32 + 2b5ede4 commit 1e5d3ea

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class NumMatrix {
2+
int[][] preSum;
3+
4+
public NumMatrix(int[][] matrix) {
5+
int m = matrix.length;
6+
int n = matrix[0].length;
7+
preSum = new int[m + 1][n + 1];
8+
9+
for (int i = 0; i < m; i++) {
10+
for (int j = 0; j < n; j++) {
11+
preSum[i + 1][j + 1] = preSum[i + 1][j] + preSum[i][j + 1] - preSum[i][j] + matrix[i][j];
12+
}
13+
}
14+
}
15+
16+
public int sumRegion(int row1, int col1, int row2, int col2) {
17+
return preSum[row2 + 1][col2 + 1] - preSum[row2 + 1][col1] - preSum[row1][col2 + 1] + preSum[row1][col1];
18+
}
19+
}
20+
21+
/**
22+
* Your NumMatrix object will be instantiated and called as such:
23+
* NumMatrix obj = new NumMatrix(matrix);
24+
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
25+
*/

0 commit comments

Comments
 (0)