303. Range Sum Query - Immutable
1. Description
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]))
2. Example
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))
3. Constraints
- 0 <= nums.length <= $10^4$
- $-10^5$ <= nums[i] <= $10^5$
- 0 <= i <= j < nums.length
- At most $10^4$ calls will be made to sumRange.
4. Solutions
My Accepted Solution
n = i_nums.size()
Init
Time complexity: O(n)
Space complexity: O(n)
Calculate
Time complexity: O(1)
Space complexity: O(1)
sumFromBeginning[i] means all values' sum from index 0 to index i
dp = sumRange
$ dp[i][j] = \begin{cases} sumFromBeginning[0], & \text{i == 0} \\
sumFromBeginning[j] - sumFromBeginning[i-1], & \text{i > 0} \\
\end{cases} $
class NumArray
{
private:
vector<int> sumFromBeginning;
public:
NumArray(vector<int> &i_nums)
{
sumFromBeginning = vector<int>(i_nums.size());
for(int i = 0; i < i_nums.size(); i++)
{
sumFromBeginning[i] = i_nums[i] + (i > 0 ? sumFromBeginning[i - 1] : 0);
}
}
int sumRange(int i, int j)
{
return sumFromBeginning[j] - (i > 0 ? sumFromBeginning[i - 1] : 0);
}
};