307. Range Sum Query - Mutable (Medium)
https://leetcode.com/problems/range-sum-query-mutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8
Note:
- The array is only modifiable by the update function.
- You may assume the number of calls to update and sumRange function is distributed evenly.
Solutions
class NumArray {
int[] nums;
int[] sums;
public NumArray(int[] nums) {
this.nums = nums;
sums = new int[nums.length];
if (nums.length == 0) {
return;
}
for (int i = 0; i < nums.length; i++) {
sums[i] = 0;
}
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = nums[i] + sums[i - 1];
}
}
public void update(int i, int val) {
if (nums.length == 0) {
return;
}
// the subsequent sums will be affected
int diff = nums[i] - val;
for (int j = i; j < nums.length; j++) {
sums[j] = sums[j] - diff;
}
nums[i] = val;
}
public int sumRange(int i, int j) {
if (nums.length == 0) {
return 0;
}
return sums[j] - sums[i] + nums[i];
}
}