Skip to content

Commit 338138c

Browse files
authored
Create 0304 Range Sum Query 2D - Immutable.md
1 parent b6549c7 commit 338138c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# 304. Range Sum Query 2D - Immutable
2+
https://leetcode-cn.com/problems/range-sum-query-2d-immutable/
3+
Given a 2D matrix matrix, handle multiple queries of the following type:
4+
Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
5+
Implement the NumMatrix class:
6+
7+
NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
8+
int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
9+
10+
Example 1:
11+
![image](https://user-images.githubusercontent.com/60777462/156893161-32c54b1f-99fc-40b6-bfd6-e13f5778db28.png)
12+
Input
13+
["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
14+
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
15+
Output
16+
[null, 8, 11, 12]
17+
18+
Explanation
19+
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
20+
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
21+
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
22+
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
23+
24+
Constraints:
25+
m == matrix.length
26+
n == matrix[i].length
27+
1 <= m, n <= 200
28+
-10^5 <= matrix[i][j] <= 10^5
29+
0 <= row1 <= row2 < m
30+
0 <= col1 <= col2 < n
31+
At most 104 calls will be made to sumRegion.
32+
33+
``` python3
34+
class NumMatrix:
35+
36+
def __init__(self, matrix: List[List[int]]):
37+
m,n=len(matrix),len(matrix[0])
38+
self.sums=[[0 for i in range(n+1)] for j in range(m+1)]
39+
for i in range(1,m+1):
40+
for j in range(1,n+1):
41+
self.sums[i][j]=matrix[i-1][j-1]+self.sums[i-1][j]+self.sums[i][j-1]-self.sums[i-1][j-1]
42+
print(self.sums)
43+
44+
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
45+
return self.sums[row2+1][col2+1]+self.sums[row1][col1]-self.sums[row2+1][col1]-self.sums[row1][col2+1]
46+
47+
48+
49+
# Your NumMatrix object will be instantiated and called as such:
50+
# obj = NumMatrix(matrix)
51+
# param_1 = obj.sumRegion(row1,col1,row2,col2)
52+
```

0 commit comments

Comments
 (0)