【发布时间】:2021-02-02 19:48:12
【问题描述】:
我正在尝试使用 python 的 TwoSum 问题,并尝试了两个指针方法,基本上在数组的开头和结尾都有一个指针,当两个索引的总和大于正在寻找它的值时,它会递减结束指针少一个索引,如果总和小于它将开始指针增加 1。我不断收到索引超出范围错误,想知道它为什么会发生。我单步执行了我的代码,一切似乎都有意义,并且我的测试用例通过了,但是当我得到这样的列表时,它给了我一个超出范围的错误:
[-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
【问题讨论】: