303. Area and Retrieval-Array Immutable (C++)
1 topic description
Given an integer array nums, find the sum of the elements in the range from index i to j (i ≤ j), including two points i and j.
Implement the NumArray class:
- NumArray(int[] nums) uses the array nums to initialize the object
- int sumRange(int i, int j) returns the sum of the elements in the array nums from index i to j (i ≤ j), including two points i and j (that is, sum(nums[i], nums[i + 1] ,…, Nums[j]))
2 Example description
输入:
[“NumArray”, “sumRange”, “sumRange”, “sumRange”]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
输出:
[null, 1, -1, -3]
解释:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
3 Problem solving tips
0 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
0 <= i <= j < nums.length
最多调用 10^4 次 sumRange 方法
4 Problem-solving ideas
Define the sum of the array from nums[0] to nums[i], but the sum of i to j must be calculated from i+1, otherwise it will fall to the last one.
5 Detailed source code (C++)
class NumArray {
public:
vector<int> sum ; //定义从nums[0]到nums[i]的数组和,但是计算i到j的和要从i+1开始算,否则会落下最后一个
NumArray(vector<int>& nums) {
sum.resize( nums.size() + 1 ) ;
for ( int i = 0 ; i < nums.size() ; i ++ )
{
sum[i + 1] = sum[i] + nums[i] ;
}
}
int sumRange(int i, int j) {
return sum[j + 1] - sum[i] ;
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/