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).
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
[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]
]
sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Note:
- The matrix is only modifiable by the update function.
- You may assume the number of calls to update and sumRegion function is distributed evenly.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
根据公式:colSums[i][j] = sum( matrix[0][j], matrix[1][j], matrix[2][j],......,matrix[i - 1][j] ).
class NumMatrix:
def __init__(self, matrix):
"""
:type matrix: List[List[int]]
"""
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return
self.matrix = matrix
row, col = len(matrix), len(matrix[0])
self.colSums = [[0 for i in range(col)] for j in range(row + 1)]
for i in range(1, len(self.matrix) + 1):
for j in range(len(self.matrix[0])):
self.colSums[i][j] = self.colSums[i - 1][j] + self.matrix[i - 1][j]
def update(self, row, col, val):
"""
:type row: int
:type col: int
:type val: int
:rtype: void
"""
for i in range(row + 1, len(self.colSums)): # 更新colsums对应位置及后面所有受影响的位置
self.colSums[i][col] = self.colSums[i][col] - self.matrix[row][col] + val
self.matrix[row][col] = val
def sumRegion(self, row1, col1, row2, col2):
"""
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
res = 0
for j in range(col1, col2 + 1):
res += self.colSums[row2 + 1][j] - self.colSums[row1][j]
return res
obj = NumMatrix(matrix=
[[1], [2]]
)
print(obj.sumRegion(0, 0, 1, 0))