来源:Leetcode Problem Set - Algorithm Problem303
题目描述:
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:
- You may assume that the array does not change.
- There are many calls to sumRange function.
解题思路:维护一个sum数组,sum中的每个元素积累从第一到第i个元素的和,输出时只需要对输入的两个index对应的sum值做差就行。
题解代码:
class NumArray {
public:
vector<int> sums;
NumArray(vector<int> nums) {
sums.resize(nums.size()+1);
int sum = 0;
sums[0] = sum;
for (int i = 0 ;i < nums.size(); i++) {
sum += nums[i];
sums[i+1] = sum;
}
}
int sumRange(int i, int j) {
return sums[j+1] - sums[i];
}
};