Skip to content

Instantly share code, notes, and snippets.

@BiruLyu
Created May 22, 2017 05:46
Show Gist options
  • Save BiruLyu/dd7699e1d5ef9e9d56b006d85e9da0e6 to your computer and use it in GitHub Desktop.
Save BiruLyu/dd7699e1d5ef9e9d56b006d85e9da0e6 to your computer and use it in GitHub Desktop.
public class NumArray {
private int[] nums;
private int[] BITree;
public NumArray(int[] nums) {
int len = nums.length;
this.nums = nums;
this.BITree = new int[len + 1];
for( int i = 0; i < len; i++){
initBITree(i, nums[i]);
}
}
public void initBITree(int i, int val){
int idx = i + 1;
while( idx < this.BITree.length){
this.BITree[idx] += val;
idx += idx & (-idx);
}
}
public void update(int i, int val) {
int len = this.nums.length;
int diff = val - this.nums[i];
this.nums[i] = val;//updated the nums[i], otherwise the calculated diff became wrong upating the same index next time
initBITree(i, diff);
}
public int getSum(int i){
int sum = 0;
i = i + 1;
while(i > 0){
sum += this.BITree[i];
i -= i & (-i);
}
return sum;
}
public int sumRange(int i, int j) {
//return this.BITree[j];
return getSum(j) - getSum(i - 1);
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(i,val);
* int param_2 = obj.sumRange(i,j);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment