-
Notifications
You must be signed in to change notification settings - Fork 9
/
rangeSumQueryImmutable.cpp
50 lines (40 loc) · 1002 Bytes
/
rangeSumQueryImmutable.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* leetcode: Range Sum Query - Immutable
* difficulty: medium
* tags: dynamic proramming
*/
#include <cstdio>
#include <vector>
using namespace std;
class NumArray {
public:
NumArray(vector<int> &nums) {
for (int i=0; i<nums.size(); ++i) {
nums_.push_back(nums[i]);
sum_.push_back(0);
}
for (int i=1; i<nums_.size(); ++i) {
sum_[i] = sum_[i-1] + nums_[i];
}
}
int sumRange(int i, int j) {
int s = (sum_[j] - sum_[i] + nums_[i]);
printf("s=%d\n", s);
return s;
}
private:
vector<int> nums_;
vector<int> sum_;
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
int main(int argc, char** argv) {
int nums1[] = {1,2,3,4,5,6};
vector<int> nums(nums1, nums1+6);
NumArray numArray(nums);
numArray.sumRange(0, 1);
numArray.sumRange(1, 2);
return 0;
}