题目描述:
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 sumRangefunction.
解题思路:题目中要求nums数组是已知且固定的,且要多次调用sumRange函数
对每个位置的求和计算进行储存,求解给定区间元素之和的时候只要对对应位置的头尾相减即可
class NumArray {
private:
vector<int> sums;
public:
NumArray(vector<int> nums) {
sums.push_back(0);
for(int i = 0; i < nums.size(); i++){
sums.push_back(nums[i] + sums[i]);
}
}
int sumRange(int i, int j) {
return sums[j+1] - sums[i];
}
};