1. Two Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
def twoSum(nums, target):
indices = {}
for i, n in enumerate(nums):
complement = target - n
if complement in indices:
return [i,indices[complement]]
indices[n] = i
assert False
def twoSumSorted(numbers, target):
left = 0
right = len(numbers) - 1
while (left < right):
s = numbers[left] + numbers[right]
if s == target:
return [left+1, right+1]
if s < target:
left += 1
else:
right -= 1
return [-1, -1]
Comments
Post a Comment