303. Range Sum Query - Immutable
作者:互联网
问题:
给定一个数组,求任意区间[left, right]的元素和。
Example 1: Input ["NumArray", "sumRange", "sumRange", "sumRange"] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] Output [null, 1, -1, -3] Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3) numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) Constraints: 1 <= nums.length <= 10^4 -10^5 <= nums[i] <= 10^5 0 <= left <= right < nums.length At most 10^4 calls will be made to sumRange.
解法:前缀和(preSum)DP
- 在初始化数组时,构建前缀和数组,
- pSum[i+1]:记录第 0~i 元素之和。
- base: pSum[0] = 0, pSum[1]=nums[0]
- 那么每次所求区间[left, right]
- 即返回 pSum[right+1]-pSum[left]
代码参考:
1 class NumArray { 2 public: 3 vector<int> pSum; 4 NumArray(vector<int>& nums) { 5 int n = nums.size(); 6 pSum.resize(n+1,0); 7 for(int i=0; i<n; i++) { 8 pSum[i+1] = pSum[i]+nums[i]; 9 } 10 } 11 12 int sumRange(int left, int right) { 13 return pSum[right+1]-pSum[left]; 14 } 15 }; 16 17 /** 18 * Your NumArray object will be instantiated and called as such: 19 * NumArray* obj = new NumArray(nums); 20 * int param_1 = obj->sumRange(left,right); 21 */
标签:right,numArray,NumArray,303,Range,sumRange,Query,pSum,left 来源: https://www.cnblogs.com/habibah-chang/p/14601155.html