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.
解题思路
考虑到要多次调用sumRange()
函数,因此需要把结果先存起来,调用时就可以直接返回了。最开始考虑的是用dp[i][j]
来直接存储i
到j
之间元素的和,但是内存超出限制。于是考虑用dp[i]
来存储0
到i
之间元素的和,0
到j
的和减去0
到i-1
的和即为所求。
实现代码
// Runtime: 3 ms
public class NumArray {
private int[] dp;
public NumArray(int[] nums) {
dp = new int[nums.length];
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
dp[i] = sum;
}
}
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 numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
时间: 2024-09-20 09:18:16