-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode304.java
33 lines (25 loc) · 949 Bytes
/
leetcode304.java
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
27
28
29
30
31
32
33
/*
Sum(ABCD)=Sum(OD)−Sum(OB)−Sum(OC)+Sum(OA)
*/
public class NumMatrix {
private int[][] sum;
public NumMatrix(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return;
int row = matrix.length;
int col = matrix[0].length;
sum = new int[row+1][col+1];
for(int i = 1; i < sum.length; i++){
for(int j = 1; j < sum[0].length; j++){
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return sum[row2+1][col2+1] - sum[row1][col2+1] - sum[row2+1][col1] + sum[row1][col1];
}
}
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);