303. 区域和检索-数组不可变
作者:互联网
/**
* 对于不可变数组,用线段树反而更麻烦
*/
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/
标签:检索,right,nums,int,sum,303,NumArray,数组,public 来源: https://www.cnblogs.com/taoyuann/p/15533248.html