• [leetcode]Range Sum Query 2D


    因为两者操作差不多,所以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)
    

      

  • 相关阅读:
    UML类图与类的关系详解
    hadoop中的Partition
    几种排序
    poj 1006
    Hadoop namenode无法启动
    String中intern的方法
    java
    模板方法模式
    里氏替换原则
    按字节数截取字符串
  • 原文地址:https://www.cnblogs.com/lautsie/p/12289932.html
Copyright © 2020-2023  润新知