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.
class NumArray {
public:
NumArray(vector<int> &nums) {
if (nums.empty())
return;
sum.push_back(nums[0]);
for (int i = 1; i < nums.size(); ++i) {
sum.push_back(sum[i - 1] + nums[i]);
}
}
int sumRange(int i, int j) {
if (0 == i)
return sum[j];
if (i > sum.size() || j > sum.size())
return 0;
return sum[j] - sum[i - 1];
}
private:
vector<int> sum;
};
本文介绍了一种针对固定数组进行多次区间求和操作的优化算法。通过预计算并存储数组的部分和,使得每次查询区间[i,j]内的元素之和可以在常数时间内完成。这种方法特别适用于数组不会发生变化但需要频繁进行区间求和的情况。
691

被折叠的 条评论
为什么被折叠?



