304. 二维区域和检索 - 矩阵不可变 - 力扣(LeetCode)
根据原始数组martix,维护一个a数组作为二维前缀和,然后通过sunRegion函数的公式可以求出左上坐标(row1,col1)右下坐标(row2,col2)的矩阵中 元素的总和
class NumMatrix { private int[][] a; public NumMatrix(int[][] matrix) { int x = matrix.length; int y = matrix[0].length; a = new int[matrix.length+1][matrix[0].length+1]; for(int i=1;i<=x;++i){ for(int j=1;j<=y;++j){ a[i][j] = matrix[i-1][j-1] + a[i-1][j]+a[i][j-1]-a[i-1][j-1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { return a[row2+1][col2+1] - a[row2+1][col1]-a[row1][col2+1] + a[row1][col1]; } } /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */
标签:前缀,int,矩阵,304,二维,length,matrix From: https://www.cnblogs.com/h404nofound/p/16736198.html