给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None
提示:
enumerate函数说明:enumerate(sequence, [start=0])
功能:将可循环序列sequence以start开始分别列出序列数据和数据下标,即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。
举例:
hashmap = {"apple", ''banana'', ''orange''}
for index,item in enumerate(hashmap):
print(index,item)
得到以下结果
0 apple
1 banana
2 orange