一、代码模板
{
sum = new int[n + 1];
for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + nums[i - 1];
//nums为原数组,sum为前缀和数组
}
// 计算 [i, j] 结果
{
ans = sum[j] - sum[i - 1];
}
//注意需要将sum的长度设置为n+1,因为将长度设置为n的话,那么sum数组中索引i的值为nums数组索引0到索引i的和,求[i,j]时,值为ans = sum[j]-sum[i-1],此代码在i==0时会报错。
二、例题(leetcode 303)
三、题解(leetcode 303)
class NumArray {
int[] sum;
public NumArray(int[] nums) {
int n = nums.length;
sum = new int[n + 1];
for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + nums[i - 1];
}
public int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/