Advertisement
lifeiteng

308. Range Sum Query 2D - Mutable

Sep 10th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. class NumMatrix {
  2.  
  3.     Fenwick[] bit;
  4.     public NumMatrix(int[][] matrix) {
  5.         int m = matrix.length;
  6.         bit = new Fenwick[m];
  7.         for(int i = 0; i < m; i++)
  8.         {
  9.             bit[i] = new Fenwick(matrix[i]);
  10.             System.out.println(Arrays.toString(bit[i].bit));
  11.         }
  12.        
  13.     }
  14.    
  15.     public void update(int row, int col, int val) {
  16.         bit[row].update(col + 1, val);
  17.     }
  18.    
  19.     public int sumRegion(int row1, int col1, int row2, int col2) {
  20.         int sum = 0;
  21.         for(int i = row1; i <= row2; i++)
  22.         {
  23.             sum += bit[i].get(col2 + 1) - bit[i].get(col1);
  24.         }
  25.         return sum;
  26.     }
  27. }
  28.  
  29. class Fenwick
  30. {
  31.     int[] bit;
  32.    
  33.     public Fenwick(int[] ary)
  34.     {
  35.         int n = ary.length, len = 1;
  36.         while(len <= n) len <<= 1;
  37.         bit = new int[len];
  38.         for(int i = 0; i < n; i++) update(i + 1, ary[i]);
  39.     }
  40.    
  41.     int get(int pos)
  42.     {
  43.         int res = 0;
  44.         while(pos > 0)
  45.         {
  46.             res += bit[pos];
  47.             pos -= pos & -pos;
  48.         }
  49.         return res;
  50.     }
  51.    
  52.     void update(int pos, int val)
  53.     {
  54.         int cur = get(pos) - get(pos - 1), diff = -cur + val;
  55.         int n = bit.length;
  56.         while(pos < n)
  57.         {
  58.             bit[pos] += diff;
  59.             pos += pos & -pos;
  60.         }
  61.     }
  62. }
  63.  
  64. /**
  65.  * Your NumMatrix object will be instantiated and called as such:
  66.  * NumMatrix obj = new NumMatrix(matrix);
  67.  * obj.update(row,col,val);
  68.  * int param_2 = obj.sumRegion(row1,col1,row2,col2);
  69.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement