1.两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
逆向思维:target减去第一个值,判断字典里存不存在,若不存在存入键值,进行第二次迭代
解法思想:此算法时间复杂度为O(n)
1.设置一个空字典 2.获取数组中nums元素长度
第一次迭代(x = 0):
-
当
x = 0
时,nums[x] = nums[0] = 2
。 -
计算
complement = target - nums[x] = 9 - 2 = 7
。 -
检查
7
是否在字典d
中:此时执行
d[2] = 0
,字典d
变为{2: 0}
。第二次迭代(x = 1):
- 当
x = 1
时,nums[x] = nums[1] = 7
。 - 计算
complement = target - nums[x] = 9 - 7 = 2
。 - 检查
2
是否在字典d
中:
- 当
class Solution(object):
def twoSum(self, nums, target):
d = {}
n = len(nums)
for x in range(n): # 0 1 2 3
if target - nums[x] in d: # 9-2=7 9-7=2 查询的是键
return d[target - nums[x]], x
else:
d[nums[x]] = x # d[2]=0 d[7]=1
nums = [2,7,11,15], target = 9
2.也可以暴力破解
class Solution(object):
def twoSum(self,nums,target):
n=len(nums)
for x in range(n):
for y in range(x+1,n):
if nums[x]+nums[y]==target:
return x,y