给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
方案一:利用字典,存储检查过的元素及其索引。
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
t = target - nums[i]
if t in d:
return [d[t], i]
d[nums[i]] = i
方案二:不使用字典,但是效率上低了许多。
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
t = target - nums[i]
if t in nums and nums.index(t) != i:
return [i, nums.index(t)]