The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
2. Implementation
(1) Binary Index Tree
class NumArray {
BIT bit;
int[] nums;
int size;
public NumArray(int[] nums) {
if (nums == null || nums.length == 0) {
return ;
}
size = nums.length;
this.nums = nums;
bit = new BIT(size);
for (int i = 0; i < size; i++) {
bit.update(i + 1, nums[i]);
}
}
public void update(int i, int val) {
bit.update(i + 1, val - nums[i]);
nums[i] = val;
}
public int sumRange(int i, int j) {
return bit.query(j + 1) - bit.query(i);
}
}
class BIT {
int[] sums;
public BIT(int n) {
sums = new int[n + 1];
}
public void update (int index, int val) {
while (index < sums.length) {
sums[index] += val;
index += index & -index;
}
}
public int query(int index) {
int sum = 0;
while (index > 0) {
sum += sums[index];
index -= index & -index;
}
return sum;
}
}
/**
* 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);
*/