题目
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.
分析及解答
目标:是 方便计算任意一个区间的距离。
导出的目标: 以 起始点为基准点,然后使得 区间的计算可以归结为距离的相减。
1.修改原数组
class NumArray {
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];
return nums[j] - nums[i - 1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
2.不修改原数组
public class NumArray {
int[] dp;
public NumArray(int[] nums) {
int len = nums.length;
dp = new int[len+1];
dp[0] = 0;
for(int i = 1; i<=len; i++){
dp[i] = dp[i-1] + nums[i-1];
}
}
public int sumRange(int i, int j) {
return dp[j+1]-dp[i];
}
}