[英]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.