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.
用一个数组存储前 i 个元素的和,并在求i-j范围内元素和的时候直接res[i]-res[j];
class NumArray {
private:
vector<int> res;
public:
NumArray(vector<int> nums) {
res = nums;
for (int i = 1; i < nums.size(); i++){
res[i] = res[i - 1] + nums[i];
}
}
int sumRange(int i, int j) {
if (i < 0 || j < 0 || i > j)return 0;
if (i == 0)return res[j];
return res[j] - res[i - 1];
}
};