Skip to content

Commit aeb4bcb

Browse files
refactor 304
1 parent fe3c343 commit aeb4bcb

File tree

1 file changed

+20
-16
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-16
lines changed

src/main/java/com/fishercoder/solutions/_304.java

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 304. Range Sum Query 2D - Immutable
5+
*
46
* Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
57
68
Range Sum Query 2D
@@ -25,30 +27,32 @@ The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) an
2527
*/
2628
public class _304 {
2729

28-
public class NumMatrix {
30+
public static class Solution1 {
31+
public class NumMatrix {
2932

30-
public NumMatrix(int[][] matrix) {
31-
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
32-
return;
33-
}
33+
public NumMatrix(int[][] matrix) {
34+
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
35+
return;
36+
}
3437

35-
/**The dimensions of this tot matrix is actually 1 bigger than the given matrix, cool!*/
36-
tot = new int[matrix.length + 1][matrix[0].length + 1];
37-
for (int i = 0; i < matrix.length; i++) {
38-
for (int j = 0; j < matrix[0].length; j++) {
39-
tot[i + 1][j + 1] = matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
38+
/**The dimensions of this tot matrix is actually 1 bigger than the given matrix, cool!*/
39+
tot = new int[matrix.length + 1][matrix[0].length + 1];
40+
for (int i = 0; i < matrix.length; i++) {
41+
for (int j = 0; j < matrix[0].length; j++) {
42+
tot[i + 1][j + 1] =
43+
matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
44+
}
4045
}
4146
}
42-
}
4347

44-
public int sumRegion(int row1, int col1, int row2, int col2) {
45-
return tot[row2 + 1][col2 + 1] - tot[row2 + 1][col1] - tot[row1][col2 + 1]
48+
public int sumRegion(int row1, int col1, int row2, int col2) {
49+
return tot[row2 + 1][col2 + 1] - tot[row2 + 1][col1] - tot[row1][col2 + 1]
4650
+ tot[row1][col1];
47-
}
51+
}
4852

49-
int[][] tot;
53+
int[][] tot;
54+
}
5055
}
51-
5256
/**
5357
* Your NumMatrix object will be instantiated and called as such:
5458
* NumMatrix obj = new NumMatrix(matrix);

0 commit comments

Comments
 (0)