Given an integer arraynums, find the sum of the elements between indicesiandj(i≤j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
題目非常簡單憾朴,所以最暴力的方法就是從數(shù)組i位置開始累加到j(luò)位置移迫,但是這樣會超時。
優(yōu)化后的方法是:遍歷nums,每個元素的位置存儲的值是此元素之前的所有元素值之和运准。當計算i與j之間的元素和時利职,只需要用j位置的元素和減去i-1位置的元素和违诗,并且注意考慮邊界條件
public class NumArray {
private int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
for(int i = 1; i < this.nums.length; i++){
this.nums[i] += this.nums[i-1];
}
}
public int sumRange(int i, int j) {
if(i > j)
return -1;
else if(i == 0)
return this.nums[j];
else
return this.nums[j] - this.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);
*/```