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.
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> &nums) {
//计算从begin~end每个位置和
if (nums.empty())
return;
else{
sum.push_back(nums[0]);
for (vector<int>::size_type index = 1; index != nums.size(); ++index){
sum.push_back(nums[index] + sum[index - 1]);
}
}
}
int sumRange(int i, int j) {
if (i == 0){
//cout << sum[j];
return sum[j];
}
else
{
//cout << sum[j] - sum[i - 1] << endl;
return(sum[j] - sum[i-1]);
}
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);