303. Range Sum Query - Immutable

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
这里写图片描述
给定一个数组,求对应索引区间的值的和。

2,题目思路
直接用for遍历来解,是有解,但是题目有一点需要注意的是,它事先定义了一个构造函数,利用构造函数来初始化向量数组,并利用另外的函数来计算这样的和。
在这种情况下,直接在构造函数中通过赋值的方式来传递向量,再在计算中利用for循环来做,会造成很大的时间消耗。
因此,在对传递的向量的处理上,有一些别的办法。
即,初始化时,定义的向量为:
numSum[i] = nums[0] + nums[1] + … + num[i-1]
注意的是,numSum[0] = 0
这样,在计算这样的索引区间和时,只要计算numSum[j+1] - numSum[i]即可。

3,程序源码

class NumArray {
public:
    NumArray(vector<int> nums) {
        int temSum = 0;
        for(auto n : nums){
            temSum += n;
            numSum.push_back(temSum);
        }

    }

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

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值