Range Sum Query - Immutable
Description
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.
Solution
sums[i]
: the sum of first i numbers.
class NumArray {
public:
NumArray(vector<int> nums) {
int n = nums.size();
sums.resize(n + 1);
sums[0] = 0;
for(int i = 0; i < n; ++i){
sums[i + 1] = sums[i] + nums[i];
}
}
int sumRange(int i, int j) {
return sums[j + 1] - sums[i];
}
vector<int> sums;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
Last updated