308. Range Sum Query 2D - Mutable
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).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
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
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Note:
- The matrix is only modifiable by the update function.
- 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:Binary Indexed Tree / Fenwich Tree
思路:
和307的基本思路一致,只是在每一行都要建一颗bit。在update的时候只需要修改本行的bit,在query的时候要将[row1, row2]范围内的query累计。
Complexity
Init the tree (include building all prefix sums) takes O(mnlogn)
Update the value of an element takes O(logn)
Query the range sum takes O(mlogn)
Space complexity: O(mn)
class NumMatrix {
private:
vector<vector<int>> vec;
vector<vector<int>> sum;
static inline int lowbit(int x) {
return x & (-x);
}
void add(int val, int x, int y) {
while (y < sum[x].size()) {
sum[x][y] += val;
y += lowbit(y);
}
}
int query(int x, int y) {
int tmp = 0;
while (y > 0) {
tmp += sum[x][y];
y -= lowbit(y);
}
return tmp;
}
public:
NumMatrix(vector<vector<int>> matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return;
vec = matrix;
int m = matrix.size(), n = matrix[0].size();
sum.resize(m, vector<int>(n + 1, 0));