The title
Given an integer array nums, find the sum of the elements in the range from index I to j (I ≤ j), including I and j.
Implement NumArray class:
Int sumRange(int I, int j) returns the sum of the elements in the range from index I to j (I ≤ j), Sum (nums[I], nums[I + 1]… The nums [j]))
Example: input: [" NumArray ", "sumRange", "sumRange", "sumRange"] [[[- 2, 0, 3, 5, 2, 1]], [0, 2], [2, 5], [0, 5]] output: [NULL, 1, -1, -3] 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 + + 2 + 3 + (5) (1)) ` ` ` tip: 0 <= nums.length <= 104-105 <= nums[I] <= 105 0 <= I <= j < nums.lengthCopy the code
class NumArray: # numArr = list() # snumArr = [0] def init(self, nums: List[int]): # self.numArr = list(nums) self.snumArr = [0] self.snumArr.append(self.snumArr[index]+val) # print(self.snumArr)
def sumRange(self, left: int, right: int) -> int: Print (self. NumArr [left:right]) # print(self. NumArr [left:right]) # print(self. NumArr [left:right]) # print(self self.snumArr[right+1] - self.snumArr[left]Copy the code
Your NumArray object will be instantiated and called as such:
obj = NumArray(nums)
param_1 = obj.sumRange(left,right)
numArray = NumArray([-2, 0, 3, -5, 2, -1])
print(numArray.sumRange(0, 2))
print(numArray.sumRange(2, 5))
print(numArray.sumRange(0, 5))
numArray = NumArray([-1]) print(numArray.sumRange(0, 0))
Copy the code