1.Question
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.
class NumArray {
private:
vector<int> dp;
public:
NumArray(vector<int> &nums) {
dp = nums;
for(int i = 1, size = nums.size(); i < size; i++)
dp[i] += dp[i-1]; //实际上也是dp[i] = dp[i-1] + nums[i]
}
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(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
3.Note
a. 这个题里我们要注意,sumRange() 会多次调用,如果直接遍历求和会超时。那么,我们用动态规划,用数组dp 记录0~i的和,表示为dp[i]。这样如果i == 0则sumRange(i, j)返回dp[j]即可, i != 0时, i~j 的和可以用dp[j] - dp[i-1]表示。
b. dp是个vector,初始化分配空间很重要。否则会出现RE.