1,题目要求
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
给定一个数组,求对应索引区间的值的和。
2,题目思路
直接用for遍历来解,是有解,但是题目有一点需要注意的是,它事先定义了一个构造函数,利用构造函数来初始化向量数组,并利用另外的函数来计算这样的和。
在这种情况下,直接在构造函数中通过赋值的方式来传递向量,再在计算中利用for循环来做,会造成很大的时间消耗。
因此,在对传递的向量的处理上,有一些别的办法。
即,初始化时,定义的向量为:
numSum[i] = nums[0] + nums[1] + … + num[i-1]
注意的是,numSum[0] = 0
这样,在计算这样的索引区间和时,只要计算numSum[j+1] - numSum[i]即可。
3,程序源码
class NumArray {
public:
NumArray(vector<int> nums) {
int temSum = 0;
for(auto n : nums){
temSum += n;
numSum.push_back(temSum);
}
}
int sumRange(int i, int j) {
return numSum[j+1] - numSum[i];
}
private:
vector<int> numSum {0};
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/