题目描述
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.
解题思路
考虑题目中提到的会多次调用sumRange函数,所以不能简单的每次计算,这样一定会超时。用空间换时间。建立一个数组,保存前i个数之和,这个数组的长度为num.length+1.下标为0的位置保存的是前0个数的和,即为0 。如题目中所给出的例子,则sum[n+1] = {0,-2,-2,1,-4,-2,-3}
代码实现
class NumArray {
private int[] sum;
public NumArray(int[] nums) {
int length = nums.length;
sum = new int [length + 1];
sum[0] = 0;
for(int i = 0; i < length; i++) {
sum[i + 1] = nums[i] + sum[i];
}
}
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);
*/