Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given an integer array nums
, handle multiple queries of the following type:
nums
between indices left
and right
inclusive where left <= right
.Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]
).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 (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
104
calls will be made to sumRange
.int[] nums;
public NumArray(int[] nums) {
for(int i = 1; i < nums.length; i++)
nums[i] += nums[i - 1];
this.nums = nums;
}
public int sumRange(int i, int j) {
if(i == 0)
return nums[j];
return nums[j] - nums[i - 1];
}
class NumArray {
public:
NumArray(vector<int> &nums) {
accu.push_back(0);
for (int num : nums)
accu.push_back(accu.back() + num);
}
int sumRange(int i, int j) {
return accu[j + 1] - accu[i];
}
private:
vector<int> accu;
};
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.accu = [0]
for num in nums:
self.accu += self.accu[-1] + num,
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.accu[j + 1] - self.accu[i]
In our experience, we suggest you solve this Range Sum Query – Immutable LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Range Sum Query – Immutable LeetCode Solution
I hope this Range Sum Query – Immutable LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>