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 尝试解
2.1 分析
给定一个整数向量arrary,输出其中任意指定区间内的数字之和。最简答的方法是将区间内的数字累加起来,但是复杂度为O(k),与区间的长度有关。可以用一个同样大小的向量SumFromLeft存储从左端到相应位置的数字之和,则sumRange(i,j)=SumFromLeft(j)-SumFromLeft(i-1)。
2.2 代码
class NumArray {
public:
vector<int> array;
vector<int> sum_from_left;
NumArray(vector<int>& nums) {
array = nums;
for(int i = 0; i < nums.size(); i++){
sum_from_left.push_back((i>0?sum_from_left[i-1]:0)+nums[i]);
}
}
int sumRange(int i, int j) {
return sum_from_left[j]-(i>0?sum_from_left[i-1]:0);
}
};
3 标准解
class NumArray {
public:
NumArray(vector<int> &nums) {
accu.push_back(0);
for (int num : nums)
accu.push_back(accu.back() + num);
}
int sumRange(int i, int j) {
return accu[j + 1] - accu[i];
}
private:
vector<int> accu;
};