/**
* 对于不可变数组,用线段树反而更麻烦
*/
class NumArray {
int[] sum;
public NumArray(int[] nums) {
/**
* 提前保存前n个元素的和,sum[i]保存的是前i个元素,不包括自身
* 区间和就是左右边界前缀和的差
*/
sum = new int[nums.length + 1];
sum[0] = 0;
for (int i = 1; i < sum.length; i++) {
sum[i] = sum[i - 1] + nums[i - 1];
}
}
public int sumRange(int left, int right) {
return sum[right + 1] - sum[left];
}
}
https://leetcode-cn.com/problems/range-sum-query-immutable/