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
前缀和思想。如果修改的次数比较多,那么就可以用线段树了,
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> nums) {
for (int i = 0; i < nums.size(); ++i) {
if (sum.size()) sum.push_back(nums[i] + sum.back());
else sum.push_back(nums[i]);
}
}
int sumRange(int i, int j) {
if (i < 1) return sum[j];
else return sum[j] - sum[i-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/