how to sum two numbers in a list?

后端 未结 7 1916
我寻月下人不归
我寻月下人不归 2021-01-29 09:17

what is the solution of this by python 3 ?

Given an array of integers, return indices of the two numbers such that they add up to a spe

7条回答
  •  温柔的废话
    2021-01-29 09:38

    We can use to pointers, at the beginning and at the end of the list to check each index by the sum of the two numbers, looping once.

    def sumOfTwo(array, target):
        i = 0
        j = len(array) - 1
        while i < j:
          add = array[i] + array[j]
          if add == target:
            return True
          elif add < target:
            i += 1
          else:
            j -= 1
        return False 
    
    input -> [1, 2, 3, 4] -> target: 6
    
     i->    <-j
    [1][2][3][4]  if i + j = target return True 
                  if i + j < target increase i
                  else decrease j
    

    Note: In a edge case, a guard of check before the loop, in case: target is a negative value, list is empty, target is null.

提交回复
热议问题