问题:
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.
解决:
①暴力破解,超时。每次求和时都计算从i到j的循环。时间复杂度O(n) ,空间复杂度O(1)。
public class NumArray {
private int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
}
public int sumRange(int i, int j) {
int sum = 0;
for (int k = i; k <= j; k ++) {
sum += nums[k];
}
return sum;
}
}
② 在预处理阶段,新建一个数组,在每个点上存储从0到当前点的值,这样当返回某范围时,就直接sum[j]-sum[i]即可,当然了,要注意是否越界。时间复杂度O(1) ,空间复杂度O(n) 。
public class NumArray {//244ms
private int sum[];
public NumArray(int[] nums) {
sum = new int[nums.length + 1];
for (int i = 1;i < sum.length ;i ++ ) {
sum[i] = sum[i - 1] + nums[i - 1];
}
}
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);
*/
进化版:直接用nums保存和。
public class NumArray { //225 ms
int[] nums;
public NumArray(int[] nums) {
for(int i = 1; i < nums.length; i ++)
nums[i] = nums[i] + nums[i - 1];
this.nums = nums; //在循环的前后都可以
}
public int sumRange(int i, int j) {
if(i == 0)
return nums[j];
return nums[j] - nums[i - 1];
}
}