题目描述
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.
题目思路
- 思路一、Note 中指出,sumRange 会多次调用,所以构造函数O(n),sumRange函数O(1)
class NumArray {
public:
vector result;
NumArray(vector& nums) {
result.push_back(0);
int n = nums.size();
int temp = 0;
for(int i=0; i < n; i++){
temp = temp + nums[i];
result.push_back(temp);
}
}
int sumRange(int i, int j) {
return result[j+1] - result[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/