注意,输出的是数在列表中的索引,所以组织字典时用这个结构 {list_value:list_index}
def two_sum(nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return None
print(two_sum([2, 7, 11, 15], 9)) # 输出:[0, 1]
print(two_sum([3, 2, 4], 6)) # 输出:[1, 2]
print(two_sum([3, 3], 6)) # 输出:[0, 1]
标签:num,sum,two,print,给定,dict,数组,目标值,complement
From: https://www.cnblogs.com/dewan/p/two_sum.html