303. 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.
s[0]=a[0]
s[1]=a[1]+s[0]
...
s[n]=a[n]+s[n-1] 将输入数组保存起来。之后通过相减即可。
需要注意的是,因为题目的(i,j)是要包括i的,所以是s[j]-s[i-1]。因此要保证i-1不为负数,所以i=0的情况单独考虑,直接输入s[j]。
同时由于要考虑输入为null的情况,也就是说迭代i要从0开始,如此一来就必须要用到一个中间变量int sum。
class NumArray {
vector<int>mynum;
public:
NumArray(vector<int> nums) {
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
mynum.push_back(sum);
}
}
int sumRange(int i, int j) {
if(i==0)
return mynum[j];
else
return mynum[j]-mynum[i-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/