Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
这道题要求可能会反复调用该方法,所以需要将加和在初始化的时候算出来, 放到一个长度为nums.length+1的sums数组里,其中 sums[0] = 0, 表示在下表为0之前的元素和为0;以此类推。每个index表示的是从开始到当前下标前的所有元素之和。
int [] nums;
int [] sums;
public NumArray(int[] nums) {
this.nums = nums;
this.sums = new int[nums.length+1];
if(nums.length>0){
sums[0] = 0;
for(int i=0;i<nums.length;i++){
//存进去
sums[i+1] = sums[i] + nums[i];
}
}
}
public int sumRange(int i, int j) {
return sums[j+1] - sums[i];
}