0%

303. Range Sum Query - Immutable

O(1) time O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class NumArray {
public:
NumArray(vector<int>& nums) {
int n = nums.size();
presum.resize(n + 1);
for (int i = 0; i < n; ++i) {
presum[i + 1] = presum[i] + nums[i];
}
}

int sumRange(int i, int j) {
return presum[j + 1] - presum[i];
}

vector<int> presum;
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/