Google
308 Range Sum Query 2D - Mutable

1. Question

Given a 2D matrixmatrix, 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.
Example:
1
Given matrix = [
2
[3, 0, 1, 4, 2],
3
[5, 6, 3, 2, 1],
4
[1, 2, 0, 1, 5],
5
[4, 1, 0, 1, 7],
6
[1, 0, 3, 0, 5]
7
]
8
9
sumRegion(2, 1, 4, 3) -> 8
10
update(3, 2, 2)
11
sumRegion(2, 1, 4, 3) -> 10
Copied!
Note:
  1. 1.
    The matrix is only modifiable by the update function.
  2. 2.
    You may assume the number of calls to update and sumRegion function is distributed evenly.
  3. 3.
    You may assume that row 1 ≤ row2 and col1 ≤ col2.

2. Implementation

(2)2D Binary Indexed Tree
思路: 二维的树状数组其实相当于每一行都是一个binary indexed tree
1
class NumMatrix {
2
BIT bit;
3
int m;
4
int n;
5
int[][] nums;
6
7
public NumMatrix(int[][] matrix) {
8
if (matrix == null || matrix.length == 0) {
9
return;
10
}
11
this.nums = matrix;
12
m = matrix.length;
13
n = matrix[0].length;
14
bit = new BIT(m, n);
15
16
for (int i = 0; i < m; i++) {
17
for (int j = 0; j < n; j++) {
18
bit.update(i, j, matrix[i][j]);
19
}
20
}
21
}
22
23
public void update(int row, int col, int val) {
24
int diff = val - nums[row][col];
25
nums[row][col] = val;
26
bit.update(row, col, diff);
27
}
28
29
public int sumRegion(int row1, int col1, int row2, int col2) {
30
return bit.query(row2 + 1, col2 + 1) - bit.query(row2 + 1, col1) - bit.query(row1, col2 + 1) + bit.query(row1, col1);
31
}
32
}
33
34
class BIT {
35
int[][] sums;
36
37
public BIT(int m, int n) {
38
sums = new int[m + 1][n + 1];
39
}
40
41
public void update(int row, int col, int val) {
42
for (int i = row + 1; i < sums.length; i += (i & -i)) {
43
for (int j = col + 1; j < sums[0].length; j += (j & -j)) {
44
sums[i][j] += val;
45
}
46
}
47
}
48
49
public int query(int row, int col) {
50
int sum = 0;
51
for (int i = row; i > 0; i -= (i & -i)) {
52
for (int j = col; j > 0; j -= (j & -j)) {
53
sum += sums[i][j];
54
}
55
}
56
return sum;
57
}
58
}
59
60
/**
61
* Your NumMatrix object will be instantiated and called as such:
62
* NumMatrix obj = new NumMatrix(matrix);
63
* obj.update(row,col,val);
64
* int param_2 = obj.sumRegion(row1,col1,row2,col2);
65
*/
Copied!

3. Time & Space Complexity

Binary Indexed Tree: 时间复杂度: Binary Indexed Tree创造: O(m * logm * n * logn), update: logm * logn, query: logm * logn