classNumArray{ privateint[] nums; privateint[] BIT; publicNumArray(int[] nums){ this.nums = nums; this.BIT = newint[nums.length + 1]; for (int i=0; i<nums.length; i++){ add(i, nums[i]); } } privatevoidadd(int k, int delt){ k++; while (k <= nums.length){ BIT[k] += delt; k += k & (-k); } } publicvoidupdate(int i, int val){ int diff = val - nums[i]; nums[i] = val; add(i, diff); } privateintgetSum(int k){ int temp = 0; k++; while (k>0){ temp += BIT[k]; k -= k & (-k); } return temp; } publicintsumRange(int i, int 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); */