Skip to content

Commit 6bc3106

Browse files
Range Sum Query 2D
1 parent 7c0329e commit 6bc3106

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package leetcode.medium;
2+
3+
public class RangeSumQuery2D {
4+
5+
private int[][] prefix;
6+
7+
public RangeSumQuery2D(int[][] matrix) {
8+
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
9+
return;
10+
}
11+
12+
int m = matrix.length;
13+
int n = matrix[0].length;
14+
15+
prefix = new int[m][n];
16+
17+
for (int i = 0; i < m; i++) {
18+
for (int j = 0; j < n; j++) {
19+
int top = (i > 0) ? prefix[i - 1][j] : 0;
20+
int left = (j > 0) ? prefix[i][j - 1] : 0;
21+
int topLeft = (i > 0 && j > 0) ? prefix[i - 1][j - 1] : 0;
22+
23+
prefix[i][j] = matrix[i][j] + top + left - topLeft;
24+
}
25+
}
26+
}
27+
28+
public int sumRegion(int row1, int col1, int row2, int col2) {
29+
int total = prefix[row2][col2];
30+
int top = (row1 > 0) ? prefix[row1 - 1][col2] : 0;
31+
int left = (col1 > 0) ? prefix[row2][col1 - 1] : 0;
32+
int topLeft = (row1 > 0 && col1 > 0) ? prefix[row1 - 1][col1 - 1] : 0;
33+
34+
return total - top - left + topLeft;
35+
}
36+
37+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class RangeSumQuery2DTest {
8+
9+
@Test
10+
void testBasicSum() {
11+
int[][] matrix = {
12+
{1, 2, 3},
13+
{4, 5, 6},
14+
{7, 8, 9}
15+
};
16+
RangeSumQuery2D rsq = new RangeSumQuery2D(matrix);
17+
assertEquals(12, rsq.sumRegion(0, 0, 1, 1)); // 1+2+4+5
18+
}
19+
20+
@org.junit.jupiter.api.Test
21+
void testEntireMatrix() {
22+
int[][] matrix = {
23+
{1, 2},
24+
{3, 4}
25+
};
26+
RangeSumQuery2D rsq = new RangeSumQuery2D(matrix);
27+
assertEquals(10, rsq.sumRegion(0, 0, 1, 1)); // 1+2+3+4
28+
}
29+
30+
@org.junit.jupiter.api.Test
31+
void testSingleElement() {
32+
int[][] matrix = {
33+
{5, 6},
34+
{7, 8}
35+
};
36+
RangeSumQuery2D rsq = new RangeSumQuery2D(matrix);
37+
assertEquals(6, rsq.sumRegion(0, 1, 0, 1)); // 6
38+
}
39+
40+
@org.junit.jupiter.api.Test
41+
void testRowQuery() {
42+
int[][] matrix = {
43+
{1, 2, 3},
44+
{4, 5, 6}
45+
};
46+
RangeSumQuery2D rsq = new RangeSumQuery2D(matrix);
47+
assertEquals(6, rsq.sumRegion(0, 0, 0, 2)); // 1+2+3
48+
}
49+
50+
@org.junit.jupiter.api.Test
51+
void testColumnQuery() {
52+
int[][] matrix = {
53+
{1, 2},
54+
{3, 4},
55+
{5, 6}
56+
};
57+
RangeSumQuery2D rsq = new RangeSumQuery2D(matrix);
58+
assertEquals(9, rsq.sumRegion(0, 0, 2, 0)); // 1+3+5
59+
}
60+
}

0 commit comments

Comments
 (0)