题目描述:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
先上暴力法,两次循环来求解:
def twoSum(nums,target):
lst = []
l = list(range(0, len(nums)))
dic = dict(zip(l,nums))
# 创建一个字典便于实现题目要求的返回下标
i = 0
while i < len(nums)+1:
j = i + 1
while j < len(nums):
if dic.get(i) + dic.get(j) == target:
lst.append(i)
lst.append(j)
return lst
j = j + 1
i = i + 1
return None
时间复杂度是n的平方,只击败了5%。
# 改进 只进行单次循环
def twoSum(nums,target):
lst = []
l = list(range(0, len(nums)))
dic = dict(zip(l,nums))
dic_hash = dict() # 同样,我们要用到hashmap的思想
i = 0
while i < len(nums):
# another 是列表中某个元素完成匹配需要的“青梅竹马” 就像把自己的意中人放在了婚姻市场
another = target - dic.get(i)
# 如果某个列表里的值 发现与婚姻市场上的意中人(key)匹配了
if dic_hash.get(dic.get(i)) is not None:
lst.append(dic_hash.get(dic.get(i)))
lst.append(i)
return lst
else:
# 你没有匹配成功 那就进入婚姻市场等待分配 这里存储的时候思路并不是常规的 "序号:值" 而是"值:序号"
dic_hash[another] = i
i = i + 1
return None
击败了67%的用户。