简体   繁体   中英

Index out of range | Python

I am attempting the TwoSum Question using python and have tried the two pointer method essentially having a pointer at the beginning and end of the array, when the sum of the two indexes is greater than the value where are looking for it decrements the ending pointer one index less and if the sum is less than it increments the beginning pointer by 1. I keep getting an index out of range error and would like to know why it happens. I stepped through my code and everything seems to make sense and my test case passes but it gives me an out of range error when I get a list like this:

  [-1,-2,-3,-4,-5] and the target being -8
  the goal is to output index positions [2,4] using the two pointer technique

Here is my code:

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

The error happens due to the logic you have built in your while loop. Whenever tempSum is larger than target, you subtract 1 from j . When working with negative numbers, this means that your loop will continue reducing j until it reaches j=-6 , at which point it will produce an out of range error.

Try taking the absolute value of tempSum and target within your if statement, then the evaluation will work in case of negative numbers as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM