题目:
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.
</pre><pre name="code" class="cpp">class NumArray {
vector<int> sums;
public:
NumArray(vector<int> &nums) {
sums=nums; //这一步缺少了就会运行错误,这是为什么?
if(nums.size()!=0){
//sums[0]=nums[0];
for(int i=1;i<nums.size();i++){
sums[i]+=sums[i-1]; //sums[i]=nums[i]+sums[i-1];这句话运行比<span style="font-family: Arial, Helvetica, sans-serif;">sums[i]+=sums[i-1];这句话快了4ms</span>
}
}
}
int sumRange(int i, int j) {
if(i>=0)
return i==0?sums[j]:(sums[j]-sums[i-1]);
else
return 0;
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
利用sums存储子序列的和,sums[i]表示nums从0到i的所有元素的和,则i、j之间的所有元素的和为:sums[j]-sums[i-1],如果i==0,则直接返回sums[j]。
运行时间592ms