LeetCode 304 二维区域和检索 - 矩阵不可变
1.题目描述:
给定一个二维矩阵 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]
2.题解:
类似于前缀和,我们把这种思想拓展到二维,即积分图,
首先初始化部分和数组f[N] [N] , f[i] [j] 表示(i,j) 左上部分区域的和。
然后我们考虑计算矩形区域的(row1, col1)和 (row2, col2)的和
即 sums[row2+1] [col2+1] - sums[row1] [col2+1] - sums[row2+1] [col1] + sums[row1] [col1] ;
时间复杂度:初始化要遍历整个数组,时间复杂度为O(n^2),
计算矩形区域的和时只需要常数次计算, 每次检索的时间复杂度为O(1)
空间复杂度:O(nm), 其中 m 和 n 分别是矩阵matrix 的行数和列数
C++:
class NumMatrix {
public:
vector<vector<int>> sums ;
NumMatrix(vector<vector<int>>& matrix) {
if ( matrix.empty() || matrix[0].empty()) return ;
int n = matrix.size(), m = matrix[0].size() ;
sums.resize(n+1, vector<int>(m+1)) ;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
sums[i+1][j+1] = sums[i][j+1]+ sums[i+1][j] - sums[i][j] + matrix[i][j] ;//初始化左上部分区域和
}
}
}
int sumRegion(int x1, int y1, int x2, int y2) {
return sums[x2+1][y2+1] - sums[x1][y2+1] - sums[x2+1][y1] + sums[x1][y1] ;
}
};
Golang:
type NumMatrix struct {
sums [][]int
}
func Constructor(matrix [][]int) NumMatrix {
m := len(matrix)
if m == 0 {
return NumMatrix{}
}
n := len(matrix[0])
sums := make([][]int, m+1)
sums[0] = make([]int, n+1)
for i, row := range matrix {
sums[i+1] = make([]int, n+1)
for j, v := range row {
sums[i+1][j+1] = sums[i+1][j] + sums[i][j+1] - sums[i][j] + v
}
}
return NumMatrix{sums}
}
func (this *NumMatrix) SumRegion(x1 int, y1 int, x2 int, y2 int) int {
return this.sums[x2+1][y2+1] - this.sums[x1][y2+1] - this.sums[x2+1][y1] + this.sums[x1][y1]
}