题目:两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
方法一:
思路就是先遍历列表里的每一个数,用target(目标值)与之做差看能不能在列表中找到对应的数,并返回它的下标。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for i in range(n):
a = target - nums[i] #作差
if a in nums: #如果差在nums列表里
b = nums.index(a) #返回差那个数值对应的下标
if b != i:
return i,b
方法二:
关键是想到用一个空字典记录差值的值和被减数的下标
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]
#用第x层去理解时,请先看else,因为这时字典d时空的。
#看完else后,我们这时来到第x+1层循环,if nums[x+1] in d,就是如果第二个数等于字典d的某个键
#这是python 字典in的语法,这时就返回对应的键值和x。还是没有就到else,
#继续增加差值和被减数的下标到字典d中,不断检验。
if nums[x] in d:
return d[nums[x]],x
#否则往字典增加键值对
else:
d[a] = x
#否则差值作为键,减去那个数的下标作为键值,加入字典,同时进入x+1层的循环,与nums[x+1]进行对比
显然第二种方法优于第一种,但是第一种比较直观。