[LeetCode] Range Sum Query - Immutable

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

思路

简单题

C++代码

Note:
You may assume that the array does not change.
There are many calls to sumRange function.

class NumArray {
    vector<int> sums;
public:
    NumArray(vector<int> &nums) {
        int s = 0;
        for (int val : nums) {
            s += val;
            sums.push_back(s);
        }
    }

    int sumRange(int i, int j) {
        int n = sums.size();
        if (i <= j && i >= 0 && j < n) {
            return sums[j] - (i > 0 ? sums[i - 1] : 0);
        }
        return 0;
    }
};