码迷,mamicode.com
首页 > 其他好文 > 详细

303. Range Sum Query - Immutable

时间:2021-04-01 12:58:58      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:return   resize   int   区间   str   iat   cal   example   param   

问题:

给定一个数组,求任意区间[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  */

 

303. Range Sum Query - Immutable

标签:return   resize   int   区间   str   iat   cal   example   param   

原文地址:https://www.cnblogs.com/habibah-chang/p/14601155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!