给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 定义一个字典来存储,数字和对应的索引(key为元素的值,value为元素的索引)。
num_dict = {}
# 循环遍历nums中的每个元素和索引
for i, num in enumerate(nums):
diff = target - num
# 判断差值是否在字典中
if diff in num_dict:
return [num_dict[diff],i]
# 不在时,将当前元素及其索引添加到字典中
num_dict[num] = I
# 找不到解,返回空列表
return []
enumerate()
是 Python 内置函数之一,它用于将一个可迭代对象转换为一个枚举对象,同时返回索引和对应的元素。例:
person=[I,you,he]
for i, per in enumerate(person):
print(i,per)
# 0 I
# 1 you
# 2 he