303. Range Sum Query - Immutable

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

class NumArray {
public:
    vector<int>sum;
    NumArray(vector<int> &nums) {
        if(nums.empty())return ;
        sum.push_back(nums[0]);
        int len=nums.size();
        for(int i=1;i<len;i++){
            sum.push_back(nums[i]+sum[i-1]);
        }
    }

    int sumRange(int i, int j) {
        if(i==0) return sum[j];
        else
           return sum[j]-sum[i-1];
    }
};


你可能感兴趣的:(303. Range Sum Query - Immutable)