The problem is as follow:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Here is how I solved it:
- We want to create a dictionary named
index_map
to store the integers innums
and their corresponding indices.
index_map = {}
- Then, we will use enumerate to get both index
i
and valuenum
of each element innums
. For each integer, let's calculate the complement, which is the difference between thetarget
and the current elementnum
.
for i, num in enumerate(nums):
n = target - num
- Now check the dictionary: if n is in the dictionary, it means we have found the two integers that add up to the
target
Return then
index and the current index as a list.
if n in index_map:
return [index_map[n], i]
- Else, if
n
is not in the dictionary, add the current elementnum
and index to the dictionary.
index_map[num] = i
Here is the completed solution:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
index_map = {}
for i, num in enumerate(nums):
n = target - num
if n in index_map:
return [index_map[n], i]
index_map[num] = i
Top comments (0)