-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRange Sum Query 2D - Immutable.java
More file actions
62 lines (46 loc) · 1.63 KB
/
Range Sum Query 2D - Immutable.java
File metadata and controls
62 lines (46 loc) · 1.63 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class NumMatrix {
int[][] matrix;
int[][] prefixSum;
public NumMatrix(int[][] matrix) {
prefixSum = new int[matrix.length][matrix[0].length];
//copy first row values
for(int i=0; i<prefixSum[0].length; i++)
prefixSum[0][i] = matrix[0][i];
//sum up column wise with corresponding matrix element
for(int i=1; i<prefixSum.length; i++)
{
for(int j=0; j<prefixSum[0].length; j++)
prefixSum[i][j] = matrix[i][j] + prefixSum[i-1][j];
}
//sum up row wise
for(int i=0; i<prefixSum.length; i++)
{
for(int j=1; j<prefixSum[0].length; j++)
prefixSum[i][j] += prefixSum[i][j-1];
}
//initialize
this.matrix = matrix;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
//with one loop
// for(int i=0; i<matrix.length * matrix[0].length; i++)
// {
// System.out.println(matrix[i/matrix.length][i%matrix[0].length]);
// }
//calculate region
int sum = prefixSum[row2][col2];
if(row1 > 0)
sum -= prefixSum[row1 -1][col2];
if(col1 > 0)
sum -= prefixSum[row2][col1-1];
if(row1 > 0 && col1 > 0)
sum += prefixSum[row1 -1][col1-1];
//return result
return sum;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/