303. Range Sum Query - Immutable (E)

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Implement the NumArray class:

NumArray(int[] nums) Initializes the object with the integer array nums.
int sumRange(int i, int j) Return the sum of the elements of the nums array in the range [i, j] inclusive (i.e., sum(nums[i], nums[i + 1], ... , nums[j]))

Example 1:

Input
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]

Explanation
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))

Constraints:

0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
At most 104 calls will be made to sumRange.


Inspired by official solutions:

class NumArray {
private:
    // vector nums_;
    vector sums_;
public:
    NumArray(vector& nums) {
        // nums_ = nums;
        int sum = 0;
        sums_.push_back(sum);
        
        for (const auto& num:nums) {
            sum += num;
            sums_.push_back(sum);
        }
    }
    
    int sumRange(int i, int j) {
        return sums_[j+1] - sums_[i];
    }
};

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

Runtime: 32 ms, faster than 69.14% of C++ online submissions for Range Sum Query - Immutable.
Memory Usage: 17.2 MB, less than 76.54% of C++ online submissions for Range Sum Query - Immutable.

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