给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
示例:
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
说明:
你可以假设数组不可变。
会多次调用 sumRange 方法。
hash表
用map表存所有的(i,j)的区域和,但会超出时间限制
class NumArray {
private:
map<pair<int,int>,int> mp;
public:
NumArray(vector<int>& nums) {
for(int i=0;i<nums.size();i++)
{
int sum=0;
for(int j=i;j<nums.size();j++)
{
sum+=nums[j];
mp.insert(make_pair(make_pair(i,j),sum));
}
}
}
int sumRange(int i, int j) {
return mp[make_pair(i,j)];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
优化版本
n[i]存0-i的区域和,(i,j)的区域和=n[j]-n[i-1];
class NumArray {
private:
int* n;
public:
NumArray(vector<int>& nums) {
if(nums.empty())
return;
n=new int[nums.size()+1];
n[0]=nums[0];
for(int i=1;i<nums.size();++i)
{
n[i]=n[i-1]+nums[i];
}
}
int sumRange(int i, int j) {
if(i==0)
return n[j];
else
return n[j]-n[i-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
最优版本
减少了函数的额外判断
class NumArray {
private:
int* n;
public:
NumArray(vector<int>& nums) {
n=new int[nums.size()+1];
n[0]=0;
for(int i=0;i<nums.size();++i)
{
n[i+1]=n[i]+nums[i];
}
}
int sumRange(int i, int j) {
return n[j+1]-n[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/