Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.
You may assume that every input has exactly one pair of indices i and j that satisfy the condition.
Return the answer with the smaller index first.
Example 1:
Input: nums = [3,4,5,6], target = 7
Output: [0,1] Explanation: nums[0] + nums[1] == 7, so we return [0, 1].
Example 2:
Input: nums = [4,5,6], target = 10
Output: [0,2] Example 3:
Input: nums = [5,5], target = 10
Output: [0,1]
In [6]:
def twosum(nums,target):
index_dict = {} #Stores value, index mapping
for i in range(len(nums)):
complement = target-nums[i]
if complement in index_dict:
return [index_dict[complement],i] #initial indexes come first
else:
index_dict[nums[i]]=i #start bulding index_dict
In [7]:
print(twosum([4,5,6],10))
[0, 2]
In [9]:
print(twosum([5,5],10))
[0, 1]