题目链接:https://leetcode.com/problems/range-sum-query-immutable/
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.
class NumArray
{
public:
NumArray(vector<int> &nums)
{
int len=(int)nums.size();
sum=new int[len];
int k=0;
for(int i=0;i<len;i++)
{
k+=nums[i];
sum[i]=k;
}
}
~NumArray()
{
delete [] sum;
}
int sumRange(int i,int j)
{
if(i==0)
return sum[j];
if(j==0)
return sum[0];
return sum[j]-sum[i-1];
}
private:
int *sum;
};