1、原题如下:
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.
2、解题如下:
class NumArray {
public:
vector<int> nums_accumulation_copy;
NumArray(vector<int> &nums) {
nums_accumulation_copy=nums;
for(int a=1;a<nums.size();a++)
{ nums_accumulation_copy[a]+=nums_accumulation_copy[a-1];
}
}
int sumRange(int i, int j) {
return (i==0)?nums_accumulation_copy[j]:(nums_accumulation_copy[j]-nums_accumulation_copy[i-1]);
}
};