303. Range Sum Query - Immutable

2018-09-26  本文已影响0人  SilentDawn

Problem

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Note:
You may assume that the array does not change.
There are many calls to sumRange function.

Example

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class NumArray {
private:
    vector<int> inner_nums;
public:
    NumArray(vector<int> nums) {
        int len = nums.size();
        inner_nums.resize(len+1,0);
        for(int i=0;i<len;i++)
            inner_nums[i+1] = inner_nums[i]+nums[i];
    }
    
    int sumRange(int i, int j) {
        return inner_nums[j+1] - inner_nums[i];
    }
};

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

Result

303. Range Sum Query - Immutable.png
上一篇 下一篇

猜你喜欢

热点阅读