• 303. Range Sum Query


    问题:

    给定一个数组,求任意区间[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  */
  • 相关阅读:
    PHP开发调试环境配置(基于wampserver+Eclipse for PHP Developers )
    关于汽车
    PCB 敷铜间距规则(转)
    有同感的话
    kubernetes学习之二进制部署1.16
    kubernetes网络之Flannel
    Kubernetes学习之原理
    Kubernetes学习之基础概念
    Centos7配置Grafana对接OpenLDAP
    Centos7安装OpenLDAP
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14601155.html
Copyright © 2020-2023  润新知