【LeetCode】Range Sum Query 2D - Immutable 二维数组范围和
Range Sum Query 2D - Immutable 二维数组范围和
题意
- You may assume that the matrix does not change.
- There are many calls to sumRegion function.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
解法
class NumMatrix(object):
def __init__(self, matrix):
"""
:type matrix: List[List[int]]
"""
self.row = len(matrix)
if not self.row:
return
self.col = len(matrix[0])
self.sums = [[0 for _ in range(self.col+1)] for _ in range(self.row+1)]
for i in range(1, self.row+1):
for j in range(1, self.col+1):
self.sums[i][j] = self.sums[i-1][j] + self.sums[i][j-1] - self.sums[i-1][j-1] + matrix[i-1][j-1]
def sumRegion(self, row1, col1, row2, col2):
"""
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
return self.sums[row2+1][col2+1] - self.sums[row2+1][col1] - self.sums[row1][col2+1] + self.sums[row1][col1]
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法



浙公网安备 33010602011771号