[英]Index out of range | Python
我正在嘗試使用 python 的 TwoSum 問題,並嘗試了兩個指針方法,基本上在數組的開頭和結尾都有一個指針,當兩個索引的總和大於正在尋找的值時,它會減少結束指針一個index less 並且如果總和小於它將開始指針增加 1。我不斷收到 index out of range 錯誤,並想知道它為什么會發生。 我逐步瀏覽了我的代碼,一切似乎都有意義,我的測試用例通過了,但是當我得到這樣的列表時,它給了我一個超出范圍的錯誤:
[-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
該錯誤是由於您在 while 循環中構建的邏輯而發生的。 只要tempSum
大於目標,就從j
中減去1
。 使用負數時,這意味着您的循環將繼續減少j
直到達到j=-6
,此時它將產生超出范圍的錯誤。
嘗試在 if 語句中tempSum
和target
的絕對值,那么在負數的情況下也可以進行評估。
if abs(tempSum) > abs(target):
j-=1
else:
i+=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.