每日leetcode-数组-304. 二维区域和检索

分类:数组-前缀和数组

题目描述:

解题思路:

  • 做这种初始化一次、检索多次的题目的秘诀:在初始化的时候做预处理。
  • 时间复杂度:构造函数的时间复杂度是 O(M * N); sumRegion 函数的时间复杂度是 O(1)
    空间复杂度:利用了preSum 矩阵,空间是 O(M * N)。

    class NumMatrix:
    
        def __init__(self, matrix: List[List[int]]):
            if not matrix or not matrix[0]:
                m,n = 0,0
            else:
                m, n = len(matrix), len(matrix[0])
            self.presum = [[0] * (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][j+1] + self.presum[i+1][j] - 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[row2+1][col1] - self.presum[row1][col2+1] + self.presum[row1][col1]
    
    # Your NumMatrix object will be instantiated and called as such:
    # obj = NumMatrix(matrix)
    # param_1 = obj.sumRegion(row1,col1,row2,
原文地址:https://www.cnblogs.com/LLLLgR/p/14815114.html