题目
给定一个二维矩阵 matrix
,以下类型的多个请求:
- 计算其子矩形范围内元素的总和,该子矩阵的 左上角 为
(row1, col1)
,右下角 为(row2, col2)
。
实现NumMatrix
类: -
NumMatrix(int[][] matrix)
给定整数矩阵matrix
进行初始化 -
int sumRegion(int row1, int col1, int row2, int col2)
返回 左上角(row1, col1)
、右下角(row2, col2)
所描述的子矩阵的元素 总和 。
输入:
["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 (蓝色矩形框的元素总和)
解题思路
- 二维前缀和:使用前缀和加快计算区域和。
二维前缀和
class NumMatrix {
int[][] preSum;
public NumMatrix(int[][] matrix) {
int n = matrix.length, m = matrix[0].length;
preSum = new int[n+1][m+1];
int[] col = new int[m];
for(int i = 0; i < n; i++) {
for(int j = 0,row = 0; j < m; j++) {
row += matrix[i][j];//i行和
col[j] += matrix[i][j];//j列的和
preSum[i+1][j+1] = preSum[i][j]+row+col[j]-matrix[i][j];//对角关系
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return preSum[row2+1][col2+1]-preSum[row2+1][col1]
-preSum[row1][col2+1] + preSum[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);
*/
复杂度分析
- 时间复杂度:
sumRegion
函数的复杂度为O(1)
,NumMatrix
的复杂度为O(mn)
,m/n
为矩阵的行/列数。 - 空间复杂度:
O(mn)
,主要为前缀和数组空间。
网友评论