题目:
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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
题目解答:这个题目说了,会反复的求一段数字的和,但是默认数组不变。这么说来,就是求和的复杂度就是主要的复杂度。那么可以先把它们存起来,然后再求得时候,直接把结果返回来。需要注意的是,求[2,5]的和就是求[0,5]的和减去[0,2]的和,再加上[2]这个位置的值。
代码如下:
class NumArray {
public: NumArray(vector<int> &nums):nums(nums) { int sum = 0; for(int i = 0;i < nums.size();i++) { sum += nums[i]; sums.push_back(sum); } }int sumRange(int i, int j) {
if((i > j) || (i >= nums.size()) || (j >= nums.size())) return 0; return sums[j] - sums[i] + nums[i]; }private:
vector<int> sums; vector<int> &nums;}; // Your NumArray object will be instantiated and called as such:// NumArray numArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);