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
Solution:
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> &nums) {
int n = nums.size();
sum = nums;
for ( int i = 1; i <= n-1; i++ ) sum[i] += sum[i-1];
}
int sumRange(int i, int j) {
int n = sum.size();
if ( i <= -1 or j >= n or i > j ) return 0;
if ( i == 0 ) return sum[j];
return sum[j]-sum[i-1];
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);