Difficulty: Easy
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.
使用空间换时间,开一个数组sum[i],表示从0~i位加起来的总和,然后sumRange(j, k)=sum[k]-sum[j-1],时间复杂度O(n)
需要特别注意nums为空时的判断和边界条件的判断
class NumArray {
public:
NumArray(vector<int> &nums) {
size=nums.size();
if(size>0)
{
sum.push_back(nums[0]);
for(int i=1;i<size;i++)
sum.push_back(sum[i-1]+nums[i]);
}
}
int sumRange(int i, int j) {
if(size==0||i>=size) return 0;//特别注意判断size==0时
if(i<=0)
{
if(j>=size) return sum[size-1];
else return sum[j];
}
if(j>=size) return sum[size-1]-sum[i-1];
else
return sum[j]-sum[i-1];
}
int size;
vector<int> sum;
};