Question:
1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
2.You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Analyze:
1、我们的目的是获取list中满足要求的index,考虑使用字典将满足条件的value和index映射起来。
2、首先创建一个空字典,用于传入列表中的值。然后遍历列表中的值(number),遍历的同时,我们可以计算出这个值需要的另一个值(加数),如本题中target=9,则number=5对应的另一个值就为4(9-5=4)。如果4不在字典中,则将number及其在列表中的索引映射并存入字典,再重复遍历判断,直到遍历到的值在字典中也恰好存在。
Code:
class Solution:
def twoSum(self,nums,target):
if len(nums) <= 1: #ensure two elements at least
return False
num_dict = {}
for i,number in enumerate(nums):
try:
return [num_dict[target-number],i] #return index
except:
num_dict[number] = i #update dict
Result: