关键在于建立一个字典用于增加计算速度
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
d = {} #创建一个空字典
for x in range(n):
a = target - nums[x] #a为差值 也是字典的key
if nums[x] in d: # 如果字典中存在num[x]则返回字典的值
return d[nums[x]],x
else:
d[a] = x #如果不存在则保存为一个新的键