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
题目描述:求数组角标在i到j之间值的和
思路:标准的一维动态规划,假设value[i]表示[0, i)范围内数值的和,那么[i,j]范围内数值的和即可表示为value[j+1]-value[i].具体代码如下:
class NumArray {
private:
int *value;
public:
NumArray(vector<int> &nums) {
int len = nums.size();
value = new int[len+1];
value[0] = 0;
for(int i = 0; i < len; ++i){
value[i+1] = value[i] + nums[i];
}
}
int sumRange(int i, int j) {
return value[j+1] - value[i];
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);