给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
示例:
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
普通解法:
class NumArray {
private:
vector<int> dp;
public:
NumArray(vector<int>& nums) {
dp = nums;
}
int sumRange(int i, int j) {
int num = 0;
while(i<=j)
{
num += dp[i];
++i;
}
return num;
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
巧妙解法:
class NumArray {
public:
NumArray(vector<int>& nums) {
if(!nums.empty())
{
_arr.push_back(nums[0]);
for(int i = 1;i<nums.size();++i)
{
_arr.push_back(_arr.back()+nums[i]);
}
}
}
int sumRange(int i, int j) {
if(i == 0)
{
return _arr[j];
}
return _arr[j]-_arr[i-1];
}
public:
vector<int> _arr;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/