題目:
Given an integer array nums, handle multiple queries of the following type:
Calculate the sum of the elements of 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]).
在已知nums這個陣列值的情況下,設計一個函式
需要left跟right參數,回傳nums裡index範圍在left~right裡的值總和
這題我選擇事先存好值加快sumRange函數的執行
class NumArray:
def __init__(self, nums: List[int]):
self.record=[]
x=0
for i in nums:
x=x+i
self.record.append(x)
def sumRange(self, left: int, right: int) -> int:
if left==0:
return self.record[right]
else:
return self.record[right]-self.record[left-1]
我們逐各個函數來解釋:
(1)init:
透過nums建立一個record陣列
裡面紀錄至該index所有陣列元素相加的值
(2)sumRange:
當left是0時我們只需要回傳record[right]即可(index 0~right的和)
而當left不是0時我們則要回傳record[right]-record[left-1]
(index left~right的和=index 0~right的和 - index 0~left-1的和)
最後執行時間84ms(faster than 93.29%)
那我們下題見