Question:
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]
Answer:
`def two_sum(nums, target):
# Create a dictionary to store the indices of elements
num_indices = {}
# Iterate through the array
for i, num in enumerate(nums):
# Calculate the complement needed to reach the target
complement = target - num
# Check if the complement exists in the dictionary
if complement in num_indices:
# Return the indices of the current element and its complement
return [num_indices[complement], I]
# Store the index of the current element in the dictionary
num_indices[num] = I
# If no solution is found, return None
return None`
Example usage:
nums1 = [2, 7, 11, 15]
target1 = 9
print(two_sum(nums1, target1)) # Output: [0, 1]
nums2 = [3, 2, 4]
target2 = 6
print(two_sum(nums2, target2)) # Output: [1, 2]
nums3 = [3, 3]
target3 = 6
print(two_sum(nums3, target3)) # Output: [0, 1]
This program defines a function two_sum that takes an array nums and a target integer target as input and returns the indices of the two numbers that add up to the target. It uses a dictionary to store the indices of elements and iterates through the array to find the complement of each element needed to reach the target. If the complement exists in the dictionary, it returns the indices of the current element and its complement. If no solution is found, it returns None. Finally, it demonstrates the usage of the function with example inputs.
Top comments (0)