March——303. 区域和检索 - 数组不可变(304)

March——303. 区域和检索 - 数组不可变(304)_第1张图片

 一维矩阵前缀和

class NumArray:

    def __init__(self, nums: List[int]):
        
        if not nums:
            return  
        self.nums = nums
        self.dp = [0]*(len(nums)+1)

        #前缀和
        for i in range(0,len(nums)):
            self.dp[i+1] = self.dp[i]+self.nums[i]

    def sumRange(self, i: int, j: int) -> int:

        return self.dp[j+1]-self.dp[i]



# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

March——303. 区域和检索 - 数组不可变(304)_第2张图片

 

 二维矩阵的前缀和

class NumMatrix:

    def __init__(self, matrix: List[List[int]]):
        if not matrix:
            return 
        self.matrix = matrix
        self.dp = [[0]*(len(matrix[0])+1) for _ in range(len(matrix)+1)]
        row,col = len(matrix),len(matrix[0])
        for i in range(row):
            for j in range(col):
                self.dp[i+1][j+1] = self.dp[i][j+1]+self.dp[i+1][j]+self.matrix[i][j]-self.dp[i][j]


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



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

 

  • 三月第一天还是比较简单的

    • 暴力法。没有超时,但是显然十分不高效

    • 前缀和,在初始化的时候计算前缀和,然后利用前缀和进行简单的减法操作,比较高效

你可能感兴趣的:(Leetcode,数组,动态规划,算法,leetcode,python)