class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {} # 弄一个字典
for i in range(len(nums)): # range 不包含区间右端点,len(nums)是nums的长度。所以正好i遍历数组。
if target - nums[i] not in dict:
dict[nums[i]] = i # 把第i个数和它的位置存在字典中 key 为 2 ,value 为 0。
else:
return [dict[target - nums[i]], i] # dict[key] 的形式来查找对应的 value
Leetcode题
最新推荐文章于 2022-10-18 16:20:03 发布