Skip to content

Commit daed7f3

Browse files
authored
Create 304. Range Sum Query 2D - Immutable
1 parent 11e67d1 commit daed7f3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

304. Range Sum Query 2D - Immutable

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

0 commit comments

Comments
 (0)