• 12.Range Sum Query


    Description:

    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

    这是一个比较简单的元素相加题目。给定一个函数,输入元素的位置参数,然后得出这个区间中的元素结果。

    具体代码如下:

    class NumArray {
    public:
      NumArray(vector<int> nums) {
        accu.push_back(0);
        for(int num : nums)
          accu.push_back(accu.back()+num);
      }

      int sumRange(int i, int j) {
        return accu[j + 1]-accu[i];
      }
    private:
      vector<int> accu;
    };

    /**
    * Your NumArray object will be instantiated and called as such:
    * NumArray obj = new NumArray(nums);
    * int param_1 = obj.sumRange(i,j);
    */

  • 相关阅读:
    DataGrip连接MySql数据库
    IDEA版本控制-Git
    IDEA关联MySql数据库
    ESXi平滑升级
    Dell服务器安装vGPU
    索引
    数据类型
    部署Zabbix监控平台
    部署Cacti监控平台
    常用系统监控命令
  • 原文地址:https://www.cnblogs.com/sarahp/p/7080868.html
Copyright © 2020-2023  润新知