Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
找出数组中的两个数,使之相加后等于target,先把数组映射为字典(方便根据value查找index),然后迭代数组,判断target减去当前数字得到的结果是否在数组(字典)中。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_dict = {value:index for (index, value) in enumerate(nums)}
for i, v in enumerate(nums):
if target-v in nums_dict and nums_dict[target-v] != i:
return([i, nums_dict[target-v]])