303 Range Sum Query - Immutable 区域和检索 - 不可变

给定一个数组,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。
例如:
给定nums = [-2, 0, 3, -5, 2, -1],求和函数为sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
注意:
    你可以假设数组不可变。
    会多次调用 sumRange 方法。
详见:https://leetcode.com/problems/range-sum-query-immutable/description/

C++:

方法一:

class NumArray {
public:
    NumArray(vector<int> nums) {
        dp=nums;
        for(int i=1;i<nums.size();++i)
        {
            dp[i]+=dp[i-1];
        }
    }
    
    int sumRange(int i, int j) {
        return i==0?dp[j]:dp[j]-dp[i-1];
    }
private:
    vector<int> dp;
};

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

 方法二:

class NumArray {
public:
    NumArray(vector<int> nums) {
        dp.resize(nums.size()+1,0);
        for(int i=1;i<=nums.size();++i)
        {
            dp[i]=dp[i-1]+nums[i-1];
        }
    }
    
    int sumRange(int i, int j) {
        return dp[j+1]-dp[i];
    }
private:
    vector<int> dp;
};

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

 参考:https://www.cnblogs.com/grandyang/p/4952464.html

posted on 2018-04-14 10:47  lina2014  阅读(186)  评论(0编辑  收藏  举报

导航