[leetcode]Range Sum Query 2D - Mutable

因为两者操作差不多,所以get和update都要O(n)

class NumMatrix:

    def __init__(self, matrix: List[List[int]]):
        if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:
            return
        m = len(matrix)
        n = len(matrix[0])
        
        self.sumRow = [[0] * n for k in range(m)] # sum of row matrix[i][:j]
        for i in range(m):
            for j in range(n):
                if j == 0:
                    self.sumRow[i][j] = matrix[i][j] 
                else:
                    self.sumRow[i][j] = self.sumRow[i][j - 1] + matrix[i][j] 
                    
        self.matrix = matrix
        

    def update(self, row: int, col: int, val: int) -> None:
        oldVal = self.matrix[row][col]
        n = len(self.matrix[0])
        self.matrix[row][col] = val
        for j in range(col, n):
            self.sumRow[row][j] += (val - oldVal)
        

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        result = 0
        for i in range(row1, row2 + 1):
            sumRight = self.sumRow[i][col2]
            if col1 > 0:
                sumLeft = self.sumRow[i][col1 - 1]
            else:
                sumLeft = 0
            sumRow = sumRight - sumLeft
            result += sumRow
        return result
            
        
        


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

  

posted @ 2020-03-31 09:43  阿牧遥  阅读(213)  评论(0编辑  收藏  举报