[LeetCode] Range Sum Query

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:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

求一个数组的范围和,可以使用动态规划来计算。

dp[x]数组表示原数组nums中前x个元素之和。如果要求nums中i~j内元素和,就要计算dp[j + 1] - dp[i]即可。

class NumArray {
public:
    NumArray(vector<int> nums) : dp(nums.size() + 1, 0) {
        for (int i = 1; i < dp.size(); i++)
            dp[i] = dp[i - 1] + nums[i - 1];
    }
    
    int sumRange(int i, int j) {
        return dp[j + 1] - dp[i];
    }
private:
    vector<int> dp; 
};
// 29 ms
/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
原文地址:https://www.cnblogs.com/immjc/p/7860559.html