Given a 2D matrixmatrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1,col1) and lower right corner (row2,col2).
The above rectangle (with the red border) is defined by (row1, col1) =(2, 1)and (row2, col2) =(4, 3), which contains sum =8.
The matrix is only modifiable by the update function.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2
The Idea: The general idea is to only accumulate on a row or column basis so that we only have to operate on the basis of either just rows or columns.
Complexity: O(n) time for both update and sum, and O(n) extra space where n is the number of columns
import numpy as npclassNumMatrix:def__init__(self,matrix):""" initialize your data structure here. :type matrix: List[List[int]] """ self.d = matrixfor row in matrix: NumMatrix.cum_sum(row)@staticmethoddefcum_sum(row):for i inrange(1, len(row)): row[i]+= row[i-1]defupdate(self,row,col,val):""" update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void """# this is the old cdf cdf = self.d[row]# can build pdf from the cdf and properly insert value prev =0 pdf = []for row_elm in cdf: pdf.append(row_elm - prev) prev = row_elm pdf[col]= val# now update the old pdffor i inrange(1, len(pdf)): pdf[i]+= pdf[i-1] self.d[row]= pdfdefsumRegion(self,row1,col1,row2,col2):""" sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int """# integral[5, 10] in discrete -> F[10] - F[5-1]# but treat this on a 2 dimensional scale right_sum, left_sum =0,0for i inrange(row1, row2+1): right_sum += self.d[i][col2]if col1 -1>=0:for i inrange(row1, row2 +1): left_sum += self.d[i][col1 -1]return right_sum - left_sum# 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)obj =NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]])print(obj.sumRegion(1,1,3,3))print(obj.sumRegion(2,2,3,3))print(obj.update(2,2,100))print(obj.sumRegion(2,2,3,3))