【问题标题】:Index out of range | Python索引超出范围 | Python
【发布时间】: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

【问题讨论】:

    标签: python arrays pointers


    【解决方案1】:

    错误是由于您在 while 循环中构建的逻辑而发生的。只要tempSum 大于目标,就从j 中减去1。处理负数时,这意味着您的循环将继续减少 j,直到达到 j=-6,此时它将产生超出范围的错误。

    尝试在 if 语句中取 tempSumtarget 的绝对值,那么在负数的情况下也可以进行评估。

    if abs(tempSum) > abs(target):
        j-=1
    else:
        i+=1
    

    【讨论】:

    • 我的错,我的意思是把目标设为-8。我快速输入了这个问题并打错了。
    猜你喜欢
    • 2017-10-02
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2016-04-17
    • 2016-07-21
    相关资源
    最近更新 更多