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 = 9Output: [0,1]Input: nums = [2,7,11,15], target = 9 Output: [0,1]Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Enter fullscreen mode Exit fullscreen mode
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6Output: [1,2]Input: nums = [3,2,4], target = 6 Output: [1,2]Input: nums = [3,2,4], target = 6 Output: [1,2]
Enter fullscreen mode Exit fullscreen mode
Example 3:
Input: nums = [3,3], target = 6Output: [0,1]Input: nums = [3,3], target = 6 Output: [0,1]Input: nums = [3,3], target = 6 Output: [0,1]
Enter fullscreen mode Exit fullscreen mode
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 = {}index_map = {}index_map = {}
Enter fullscreen mode Exit fullscreen mode
- 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 - numfor i, num in enumerate(nums): n = target - numfor i, num in enumerate(nums): n = target - num
Enter fullscreen mode Exit fullscreen mode
- 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]if n in index_map: return [index_map[n], i]if n in index_map: return [index_map[n], i]
Enter fullscreen mode Exit fullscreen mode
- Else, if
n
is not in the dictionary, add the current elementnum
and index to the dictionary.
index_map[num] = iindex_map[num] = iindex_map[num] = i
Enter fullscreen mode Exit fullscreen mode
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 - numif n in index_map:return [index_map[n], i]index_map[num] = iclass 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] = iclass 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
Enter fullscreen mode Exit fullscreen mode
暂无评论内容