-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
68 lines (59 loc) · 1.62 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}
class NumMatrix {
private BinaryIndexedTree[] trees;
public NumMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
trees = new BinaryIndexedTree[m];
for (int i = 0; i < m; ++i) {
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int j = 0; j < n; ++j) {
tree.update(j + 1, matrix[i][j]);
}
trees[i] = tree;
}
}
public void update(int row, int col, int val) {
BinaryIndexedTree tree = trees[row];
int prev = tree.query(col + 1) - tree.query(col);
tree.update(col + 1, val - prev);
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int s = 0;
for (int i = row1; i <= row2; ++i) {
BinaryIndexedTree tree = trees[i];
s += tree.query(col2 + 1) - tree.query(col1);
}
return s;
}
}
/**
* 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);
*/