1 - Two Sum
Written on May 14, 2017
Tweet
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.
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_index = {}
for i, num in enumerate(nums):
diff = target - num
if diff in num_index:
return [num_index.get(diff), i]
else:
num_index[num] = i
return []