- Range Sum Query 2D - Mutable
中文English
Given a 2D matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). And the elements of the matrix could be changed.
You have to implement three functions:
NumMatrix(matrix) The constructor.
sumRegion(row1, col1, row2, col2) Return the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
update(row, col, val) Update the element at (row, col) to val.
Example
Example 1:
Input:
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]]
)
sumRegion(2,1,4,3)
update(3,2,2)
sumRegion(2,1,4,3)
Output:
8
10
Example 2:
Input:
NumMatrix([[1]])
sumRegion(0, 0, 0, 0)
update(0, 0, -1)
sumRegion(0, 0, 0, 0)
Output:
1
-1
Notice
The matrix is only modifiable by update.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2.
解法1:树状数组2D版
代码如下:
class NumMatrix {
public:
NumMatrix(vector<vector<int>> matrix) {
nRow = matrix.size();
nCol = matrix[0].size();
A = matrix;
C.resize(nRow + 1, vector<int>(nCol + 1, 0));
for (int i = 0; i < nRow; ++i) {
for (int j = 0; j < nCol; ++j) {
add(i, j, A[i][j]);
}
}
}
void update(int row, int col, int val) {
add(row, col, val - A[row][col]);
A[row][col] = val;
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sum(row2, col2) - sum(row1 - 1, col2) - sum(row2, col1 - 1) + sum(row1 - 1, col1 - 1);
}
private:
vector<vector<int>> C, A;
int nRow, nCol;
int lowbit(int x) {
return x & -x;
}
int sum(int x, int y) {
int result = 0;
x++; y++;
for (int i = x; i > 0; i -= lowbit(i)) {
for (int j = y; j > 0; j -= lowbit(j)) {
result += C[i][j];
}
}
return result;
}
void add(int x, int y, int val) {
x++; y++;
//int delta = val - A[x][y];
for (int i = x; i <= nRow; i += lowbit(i)) {
for (int j = y; j <= nCol; j += lowbit(j)) {
C[i][j] += val;
}
}
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* obj.update(row,col,val);
* int param_2 = obj.sumRegion(row1,col1,row2,col2);
*/
解法2:线段树
TBD