【题目描述】
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.
Subscribe to see which companies asked this question
略,dp
不过在看discuss的时候学到了一个函数partial_sum() ,记录下用法学习下~
partial_sum (beg, end, dest) ;
操作前:[beg,end)标示输入序列.[dest,end)标示输出序列.
操作后:将输入序列中每个元素与其先前所有元素的和写入对应位置的输出序列中.
返回值:返回指向输出序列中被写入值的元素的下一个位置的迭代器.
备注: 必须保证输出序列至少与输入序列一样大,否则将抛出异常.
【代码】
class NumArray {
public:
vector<int> dp;
NumArray(vector<int> &nums):dp(nums.size()+1,0) {
if(nums.size()!=0){
dp[0]=nums[0];
for(int i=1;i<nums.size();i++){
dp[i]=dp[i-1]+nums[i];
}
}
}
int sumRange(int i, int j) {
if(i==0) return dp[j];
else return dp[j]-dp[i-1];
}
};