1、题目
链接:https://leetcode.com/problems/range-sum-query-2d-immutable/
内容:
Given a 2D matrix matrix, 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.
样例:Given 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] ] sumRegion(2, 1, 4, 3) -> 8 sumRegion(1, 1, 2, 2) -> 11 sumRegion(1, 2, 2, 4) -> 12
注意:
- You may assume that the matrix does not change.
- There are many calls to sumRegion function.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
2、分析
这里我们采取与一维类似的情况,因为调用sumRegion函数的次数很多,所以不能在构造函数中简单的进行赋值。我们申请一个同样大小的数组,该数组中每个元素matrix[i][j]存储的是其左上角所有元素的和(包括该元素),如上图。这下我们要计算给出的例子就简单了。
这里我们如果需要计算上面指定区域的和就可以用这个公式:matrix[4][3] - matrix[1][3] - matrix[4][0] + matrix[1][0]。然后这里需要注意一下边界的情况就可以了。
3、代码
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
int sum = 0;
for (int i = 0; i < matrix.size(); i++) {
vector<int> row;
sum = 0;
for (int j = 0; j < matrix[i].size(); j++) {
sum += matrix[i][j];
if (i == 0) {
row.push_back(sum);
} else {
row.push_back(sum + this->matrix[i - 1][j]);
}
}
this->matrix.push_back(row);
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int res = 0;
if (row1 != 0 && col1 != 0) {
res = matrix[row2][col2] - matrix[row1 - 1][col2] - matrix[row2][col1 - 1] + matrix[row1 - 1][col1 - 1];
} else if (row1 == 0 && col1 != 0) {
res = matrix[row2][col2] - matrix[row2][col1 - 1];
} else if (row1 != 0 && col1 == 0) {
res = matrix[row2][col2] - matrix[row1 - 1][col2];
} else {
res = matrix[row2][col2];
}
return res;
}
private:
vector<vector<int>> matrix;
};