# 303. Range Sum Query - Immutable

## 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:
1.You may assume that the array does not change.
2.There are many calls to sumRange function.

Analysis:

unsigned int k=0;
cout<<k-1;

Source Code（C++）:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class NumArray {
public:
vector<int> nums_sum;
NumArray(vector<int> &nums) {
int temp_sum=0;
for(int i=0; i<nums.size(); i++) {
temp_sum +=nums.at(i);
nums_sum.push_back(temp_sum);
}
}
int sumRange(int i, int j) {
if (i<0 || j>=nums_sum.size() || i>j){
return 0;
}
if (i==0){
return nums_sum.at(j);
}
else {
return nums_sum.at(j)-nums_sum.at(i-1);
}
}
};

int main() {
vector<int> nums;
nums.push_back(-2);
nums.push_back(0);
nums.push_back(3);
nums.push_back(-5);
nums.push_back(2);
nums.push_back(-1);
NumArray numArray(nums);
cout << numArray.sumRange(0, 2);
cout << numArray.sumRange(0, 5);
return 0;
}

11-19 1084

11-08 143

04-03 103

12-04 3808

11-10 1862

06-21 10

12-02 248

06-04 1962

11-30 102

12-22 372