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.
Subscribe to see which companies asked this question
1. 最开始这个题目下面的代码是这样子的:
public class NumArray {
int[] prefixSum;
public NumArray(int[] nums) {
}
public int sumRange(int i, int j) {
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
最开始的想法有点儿脑残,觉得sumRange不就是相加一下就好了嘛。可是并不明白NumArray存在的意义。
现在看来,NumArray numArray = new NumArray(nums) 这个步骤之后,nums这个参数并不能传递给sumRange这个函数,所以要想办法把参数传递过去。
2. 我写了一个版本是这样子的
public class NumArray {
int[] a;
public NumArray(int[] nums) {
int len = nums.length;
a = new int[len];
for(int i = 0; i < len; i++)
a[i] = nums[i];
}
public int sumRange(int i, int j) {
int res = 0;
for(int k = i; k <= j; k++)
res += a[k];
return res;
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
我想的是,将nums数组赋值给全局变量数组a,那么函数sumRange每次就都可以直接调用a了,这样参数就可以传递好了。但速度太慢了。。。再看下题目,sumRange会调用很多很多次,所以每一次都要遍历数组。所以重新写一下。
3. 重新写了一下是这样子的
public class NumArray {
int[] prefixSum;
public NumArray(int[] nums) {
int len = nums.length;
prefixSum = new int[len+1];
prefixSum[0] = 0;
for(int i = 1; i <= len; i++){
prefixSum[i] = prefixSum[i-1] + nums[i-1];
}
}
public int sumRange(int i, int j) {
return (prefixSum[j+1] - prefixSum[i]);
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
这里面的小trick, prefixSum 长度比nums多一。
这样不论i和j取值为几,都可以用一个减法解决。不然i=0的情况,是不需要减去前面数字的情况,还需要再判断,代码会很不清晰,逻辑更复杂,速度也会变慢。