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)的时候返回dp[j]-dp[i-1]。
class NumArray {
private int[] dp;
public NumArray(int[] nums) {
int len = nums.length;
dp = new int[len];
if(len>0)dp[0] = nums[0];
for(int i=1;i<len;i++){
dp[i] = dp[i-1] + nums[i];
}
}
public int sumRange(int i, int j) {
return i == 0 ? dp[j]:dp[j]-dp[i-1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/