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.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
题解:
这道题给定了一个整数数组nums,需要求nums[i]和nums[j]之间的所有数(包括nums[i]和nums[j])之和。
这道题其实总体思路很简单,运用了最简单的动态规划。只需要定义一个vector sum来存放每一个nums中从头加到这一位的所有数字之和。不过这里有一点要注意的地方就是sum[i]不能和nums[i]直接对等,因为由于计算从0到i的nums之和时,sum[0]为0而非nums[0],因此最后计算和的时候也需要注意是nums[j+1]。
代码:
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> nums) {
sum.push_back(0);
for (int i = 0; i < nums.size(); i++)
{
sum.push_back(sum.back() + nums[i]);
}
}
int sumRange(int i, int j) {
return (sum[j + 1] - sum[i]);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/