这道题目让实现一个方法计算数组中两个index之间的数字的和,看似非常简单,只要把之间所有的数字加起来即可。但是题目中给出的一个note是这个方法会调用很多次,所以我们希望找到一种在时间复杂度上更加有效的方法。
我们可以另外申请一个数组,数组从index为1开始,都是num[i] + nums[i - 1],这样这个新的数组index为i的元素都是nums数组中从0到i的数字的和。所以在实现新的sumRange的时候,如果i == 0,那么直接返回新的数组newArray的index为j的元素即可;而如果i不为0的时候,我们只要用newArray[j] - newArray[i - 1]即可,因为newArray[j] = sum(0...j), newArray[i - 1] = sum(0...i - 1),所以newArray[j] - newArray[i - 1] = sum(i...j),整体的代码如下;
public class NumArray {
private int[] nums;
public NumArray(int[] nums) {
for(int i = 1; i < nums.length; i++){
nums[i] += nums[i - 1];
}
this.nums = nums;
}
public int sumRange(int i, int j) {
if(i == 0) return nums[j];
else return nums[j] - nums[i - 1];
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);