problem
solution
- brute forces
1 | class NumArray { |
- prefix sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class NumArray {
private:
vector<int> preSum;
public:
NumArray(vector<int>& nums) {
// -2 0 3 -5 2 -1
// 0 -2 -2 1 -4 -2 -3
int n = nums.size();
preSum = vector<int>(n+1,0);
for(int i=1;i<n+1;++i){
preSum[i] = preSum[i-1] + nums[i-1];
}
}
int sumRange(int left, int right) {
return preSum[right+1] - preSum[left];
}
};analysis
sumRange
函數 time complexityO(1)