类别:
题目:
法一:直接计算
代码:
class NumArray {
int[] nums;
public NumArray(int[] nums) {
this.nums=nums;
}
public int sumRange(int left, int right) {
int sum = 0;
for (int i = left; i <= right; i++) {
sum += nums[i];
}
return sum;
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
结果:
法二:优化一下
每次计算sumRange都要从i遍历到j相加,不如先计算前缀和,再相减。
代码:
class NumArray {
int[] sums;
public NumArray(int[] nums) {
//计算前缀和
int n=nums.length;
sums=new int[n+1];
sums[0]=nums[0];
for (int i = 0; i < n; i++) {
sums[i+1]=sums[i]+nums[i];
}
}
public int sumRange(int left, int right) {
//做减法
return sums[right+1]-sums[left];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
结果: