简体   繁体   中英

how to solve two sum problem with python in O(n) time complexity with an array that include negative integers

I am currently learning dynamic programming and i amlooking for a solution to the 2 sum python problem in O(n) time complexity. Please note that the array include negative integers

arr = [2,-1,4,7,11]

using the two pointers method

target = 10 # sum of (-1,11)

def two_sum(arr, target):
  arr.sort()
  left = 0
  right = len(arr)-1
  while left < right:
    current_sum = arr[left] + arr[right]
    if current_sum == target:
       return [arr[left], arr[right]]
    elif current_sum < target:
      left += 1
    elif current_sum > target:
      right -= 1
  return []

# time complexity 0(n log(n))
# space complexity 0(log 1)

Unfortunately, the solution I have above is in 0(n log(n)) time complexity.

what would be the dynamic programming approach to achieve the above in 0(n) time complexity?

my current dynamic programming approach solution only work when the array is made of only non negative integers.

example

dynamic programming

arr = [1,2,4,6] # non negative integers
target = 3

def two_sum(arr, target):
  seen = {}
  for idx, value in enumerate(arr):
    remaining = target - value
    if remaining in seen:
      return [seen[remaining], value]
    seen[idx] = value
  return []

Here a solution to get all solutions

target = 10  # sum of (-1,11)
arr = [-1,3,2,4,7,11]

def twoSum(arr, target):
    number_bonds = {}
    res=[]
    for index, value in enumerate(arr):
        if value in number_bonds:
            res.append([arr[number_bonds[value]], arr[index]])
        number_bonds[target - value] = index
    return res

print(twoSum(arr,target))

the idea is to compute the number that is missing by computing the difference between the current value end the target value. the difference is stack in number_bonds

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