问题描述:
给定一个含有n个整数的数组,求出三个数,满足关系x = a + b,的组合,返回a和b的索引值,
示例:
给定 listnum = [7,2,6,8,15], target = 15
因为 listnum[0] + listnum[3] = 7 + 8 = 15
所以返回 [0, 3]
解题思路:使用字典
构建一个字典,任意找一个元素num,使target-num为字典的键,让元素num的位置为键的值,
对于列表中其他每个元素,都要判断是否在字典中,如果在字典中,则找到另外一个元素,
如果不在字典中,则字典中继续添加Dict[target-num]=i,i为索引。
具体步骤如下:
def twoSum(nums,target):
dict = {}
for i ,num in enumerate(nums):
if num in dict:
return [dict[num],i]
else:
dict[target - num ] = i
listnum = [7,2,6,8,15]
twoSum(listnum,15)
Out[17]: [0, 3]
https://leetcode-cn.com/problems/two-sum/comments/,这里是另外一种写法,
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
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:可以同时获得索引和索引对应的值
listnum = ['a','b','c']
for i in range(len(listnum)):
print(i,listnum[i])
0 a
1 b
2 c
listnum = ['a','b','c']
for i ,num in enumerate(listnum):
print(i,num)
0 a
1 b
2 c