题目: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
难度:easy 通过率:26.0%
这道题借用一个数组记录从第0项加到第i项的和t[i],然后在return的时候直接减掉多余的项即可。算法复杂度:O(n)
class NumArray {
public:
vector<int> t;
NumArray(vector<int> &nums) {
t = vector<int>(nums.size(), 0);
for(int i = 0; i < nums.size(); i++) {
if(i > 0) t[i] = t[i-1]+nums[i];
else t[0] = nums[0];
}
}
int sumRange(int i, int j) {
if(i == 0) return t[j];
return t[j]- t[i-1];
}
};