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
一刷
题解:
定数组,求range之内的数组和。 我们可以新建一个dp数组来保存数据,dp[i]表示 0到i-1这i个数的sum,每次我们就可以在使用O(n)初始化之后,用O(1)的时间得到搜索结果了。
public class NumArray {
int[] dp;
public NumArray(int[] nums) {
dp = new int[nums.length+1];
for(int i=1; i<=nums.length; i++){
dp[i] = dp[i-1]+nums[i-1];
}
}
public int sumRange(int i, int j) {
return dp[j+1]-dp[i];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
二刷
同上
class NumArray {
int[] sum;
public NumArray(int[] nums) {
sum = new int[nums.length];
int res = 0;
for(int i=0; i<nums.length; i++){
res += nums[i];
sum[i] = res;
}
}
public int sumRange(int i, int j) {
if(i==0) return sum[j];
else return sum[j] - sum[i-1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/