目录
1. 两数之和
题目描述:
题目解析
方法一:暴力枚举
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
方法二:使用字典存储遍历结果
思路: 空字典作为哈希表,其中键为 n n n,值为下标 i i i。 f o r for for 循环遍历 n u m s nums nums中的下标 i i i,及相应 n n n ,判断 ( t a r g e t − n ) (target-n) (target−n)对应的值是否在字典中,如果在字典中,直接返回下标值列表 [ d c t [ t a r g e t − n ] , i ] [dct[target-n],i] [dct[target−n],i],否则将这个数及对应下标存储到哈希表中 d c t [ t a r g r t − n ] = i dct[targrt-n]=i dct[targrt−n]=i。
2022-03-31写
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
haxitable = {}
for i,num in enumerate(nums):
if (target-num) in haxitable:
return [haxitable[target-num],i]
else:
haxitable[num] = i
return []
更早之前写的,和上面一样,看一个就好
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i,n in enumerate(nums):
cp = target - n
if cp in dct: # 判断字典中有无符合条件的值
return [dct[cp],i]
else: # 遍历列表时,将每一个数及下标存到字典中
dct[n] = i # 切记先判断再添加,以免key冲突