1. 和为s的两个数字
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。
方法一:
def twoSum(nums, target):
left = 0
right = len(nums) - 1
while True:
res = nums[left] + nums[right]
if res == target:
return [nums[left], nums[right]]
elif res > target:
right -= 1
else:
left += 1
方法二:
def twoSum(nums, target):
num_dict = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [nums[num_dict[complement]], num]
num_dict[num] = index
return []
方法三:
def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [nums[i], nums[j]]
return []
标签:right,return,target,nums,Study,num,Algorithms,Plan,dict
From: https://blog.csdn.net/qq_24058289/article/details/142371661