我正在嘗試使用python的TwoSum問題,并且嘗試了兩個指針方法,基本上在數(shù)組的開始和結(jié)束處都有一個指針,當(dāng)兩個索引的和大于查找它的值時,將結(jié)束指針減一個索引,如果和小于,則增加開始指針1。我不斷得到一個索引超出范圍的錯誤,想知道為什么會發(fā)生。我瀏覽了我的代碼,一切似乎都有意義,我的測試用例通過了,但當(dāng)我得到這樣一個列表時,它會給我一個超出范圍的錯誤:
[-1,-2,-3,-4,-5] and the target being -8
the goal is to output index positions [2,4] using the two pointer technique
這是我的密碼:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
stack = list()
n = len(nums)
j = (len(nums)-1)
i = 0
while i < n:
tempSum = nums[i] + nums[j]
if tempSum == target:
stack.append(i)
stack.append(j)
break
if tempSum > target:
j-=1
else:
i+=1
return stack
錯誤的發(fā)生是由于while循環(huán)中構(gòu)建的邏輯造成的。每當(dāng)
tempSum
大于目標(biāo)值時,就從j
中減去1
。當(dāng)使用負(fù)數(shù)時,這意味著循環(huán)將繼續(xù)減少j
,直到達(dá)到j=-6
,此時將產(chǎn)生一個超出范圍的錯誤。嘗試在if語句中取
tempSum
和target
的絕對值,那么在負(fù)數(shù)的情況下也可以進(jìn)行計算。