6/11 每日一題(自定義)
Given an integer array nums, handle multiple queries of the following type:
- Calculate the sum of the elements of
numsbetween indicesleftandrightinclusive whereleft <= right.
Implement the NumArray class:
NumArray(int[] nums)Initializes the object with the integer arraynums.int sumRange(int left, int right)Returns the sum of the elements ofnumsbetween indicesleftandrightinclusive (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] <= 1050 <= left <= right < nums.length- At most
104calls will be made tosumRange.
-------
class NumArray:
def __init__(self, nums: List[int]):
self.nums=nums #將一個整數列表nums作為參數儲存在self.nums中
def sumRange(self, left: int, right: int) -> int:
#選取範圍內的list
range_arry=self.nums[left:right+1]
return sum(range_arry) #返回範圍內的列表總和
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
--參考解答
class NumArray:
def __init__(self, nums: List[int]):
arr = [nums[0]]
for i in range(1,len(nums)):
arr.append(arr[-1]+nums[i])
self.arr = arr
def sumRange(self, left: int, right: int) -> int:
if left == 0:
return self.arr[right]
return self.arr[right] - self.arr[left - 1]
------------class NumArray:
def __init__(self, nums: List[int]):
self.nums=[0]+list(accumulate(nums))
print(self.nums)
def sumRange(self, left: int, right: int) -> int:
return self.nums[right+1]-self.nums[left]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁