leetcode每日一题—304.二维区域和检索 - 矩阵不可变

题目:
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
leetcode每日一题—304.二维区域和检索 - 矩阵不可变_第1张图片
上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。
leetcode每日一题—304.二维区域和检索 - 矩阵不可变_第2张图片
解答:

class NumMatrix:
    def __init__(self, matrix: List[List[int]]):
        m=len(matrix)
        if m>0:
            #presum比matrix 多1行1列,且presum的第一行和第一列均为0
            n=len(matrix[0])
            self.presum=[[0 for _ in range(n+1)] for _ in range(m+1)]
            for i in range(m):
                for j in range(n):
                    self.presum[i+1][j+1]=self.presum[i+1][j]+self.presum[i][j+1]-self.presum[i][j]+matrix[i][j]


    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return self.presum[row2+1][col2+1]+self.presum[row1][col1]-self.presum[row1][col2+1]-self.presum[row2+1][col1]

# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)

你可能感兴趣的:(leetcode,Python)