Skip to content

Commit 6ed0eb0

Browse files
authored
304.NumMatrix-二维前缀和
1 parent 280eab0 commit 6ed0eb0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

NumMatrix.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class NumMatrix {
2+
private int[][] sums;
3+
4+
public NumMatrix(int[][] matrix) {
5+
int m = matrix.length;
6+
int n = matrix[0].length;
7+
if(m==0 || n==0) return;
8+
sums = new int[m+1][n+1];
9+
for(int i=0; i<m; i++) {
10+
for(int j=0; j<n; j++) {
11+
sums[i+1][j+1] = sums[i][j+1] + sums[i+1][j] - sums[i][j] + matrix[i][j];
12+
}
13+
}
14+
}
15+
16+
public int sumRegion(int row1, int col1, int row2, int col2) {
17+
return sums[row2+1][col2+1] - sums[row1][col2+1] - sums[row2+1][col1] + sums[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)