1 public class NumMatrix {
 2     private int[][] matrix;
 3     private int[][] tree;
 4 
 5     public NumMatrix(int[][] matrix) {
 6         if (matrix.length == 0 || matrix[0].length == 0) {
 7             return;
 8         }
 9         this.tree = new int[matrix.length + 1][matrix[0].length + 1];
10         this.matrix = new int[matrix.length][matrix[0].length];
11         for (int i = 0; i < matrix.length; i++) {
12             for (int j = 0; j < matrix[0].length; j++) {
13                 update(i, j, matrix[i][j]);
14             }
15         }
16     }
17 
18     public void update(int row, int col, int val) {
19         if (matrix == null) {
20             return;
21         }
22         int diff = val - matrix[row][col];
23         matrix[row][col] = val;
24         
25         for (int i = row+1; i <= matrix.length; i += (i & -i)) {
26             for (int j = col+1; j <= matrix[0].length; j += (j & -j)) {
27                 tree[i][j] += diff;
28             }
29         }
30     }
31 
32     int getSum(int row, int col) {
33         int sum = 0;
34         for (int i = row+1; i > 0; i -= (i & -i)) {
35             for (int j = col+1; j > 0; j -= (j & -j)) {
36                 sum += tree[i][j];
37             }
38         }
39         return sum;
40     }
41 
42     public int sumRegion(int row1, int col1, int row2, int col2) {
43         if (matrix == null) {
44             return 0;
45         }
46         return getSum(row2, col2) + getSum(row1-1, col1-1) - getSum(row2, col1-1) - getSum(row1-1, col2);
47     }
48 }
49 
50 
51 // Your NumMatrix object will be instantiated and called as such:
52 // NumMatrix numMatrix = new NumMatrix(matrix);
53 // numMatrix.sumRegion(0, 1, 2, 3);
54 // numMatrix.update(1, 1, 10);
55 // numMatrix.sumRegion(1, 2, 3, 4);

 

 

Binary index tree: https://www.topcoder.com/community/data-science/data-science-tutorials/binary-indexed-trees/

posted on 2016-07-06 06:00  keepshuatishuati  阅读(194)  评论(0编辑  收藏  举报