给定一个二维矩阵 matrix,以下类型的多个请求:
计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2) 。
实现 NumMatrix 类:
NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行初始化
int sumRegion(int row1, int col1, int row2, int col2) 返回左上角 (row1, col1) 、右下角 (row2, col2) 的子矩阵的元素总和。
示例 1:
输入:
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[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]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
输出:
[null, 8, 11, 12]
解释:
NumMatrix numMatrix = new 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]]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (红色矩形框的元素总和)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (绿色矩形框的元素总和)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和)
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/O4NDxx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java:
方法一:基本思路:最直观的思路,直接从左上边界到右下边界遍历,计算和;
class NumMatrix {
public int[][] mat;
public NumMatrix(int[][] matrix) {
//给定二维数组,对二维数组进行初始化
// [[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]]]
this.mat = matrix;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int total = 0;
//求取给定下标的值
for(int i = row1;i <= row2 ; i++){
for(int j = col1;j<=col2;j++){
total += this.mat[i][j];
}
}
return total;
}
}
方法二:二维前缀和
java:
class NumMatrix {
public int[][] preSumMat;
public NumMatrix(int[][] matrix) {
//给定二维数组,对二维数组进行初始化
// [[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]]]
//在计算后面元素的前缀和,可以复用已经计算好了的前缀和;
//经过计算,当前元素的前缀和为 :
//preSumMat[i][j] = matrix[i][j] + preSumMat[i][j-1] +preSumMat[i-1][j] - preSumMat[i-1][j-1]
//为了不特殊处理当 0行和0列元素 下标越界问题,直接初识前缀和矩阵多初始化一行和一列,所以length+1
//初始化,直接存储输入的前缀和矩阵,
this.preSumMat = new int[matrix.length+1][matrix[0].length+1];
//遍历matrix填充前缀和矩阵
for(int i= 0; i< matrix.length; i++){
for(int j = 0 ; j < matrix[0].length ; j++){
this.preSumMat[i+1][j+1] = matrix[i][j] + this.preSumMat[i+1][j]+this.preSumMat[i][j+1] - this.preSumMat[i][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
//直接通过存储的前缀和公式进行计算
//不加1等情形: this.preSumMat[row2][col2]-this.preSumMat[row1-1][col2]-this.preSumMat[row2][col1-1]+this.preSumMat[row1-1][col1-1]
return this.preSumMat[row2+1][col2+1] - this.preSumMat[row1][col2+1] -this.preSumMat[row2+1][col1] +this.preSumMat[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);
*/
图解图片来自:
力扣https://leetcode.cn/problems/O4NDxx/solution/offerii013er-wei-zi-ju-zhen-de-he-by-log-lpt4/考题来自: