166k views
0 votes
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]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
***** write in python

2 Answers

5 votes

Final answer:

To find two indices in an array that add up to a given target, a hash map can efficiently track complements of elements against the target. The function checks for each element's complement in the hash map, and upon finding, returns the indices of the original and complement elements.

Step-by-step explanation:

To solve the problem where you are given an array of integers nums and an integer target, and you need to find indices of the two numbers such that they add up to target, you can use a brute force approach or a more efficient approach using a hash map in Python. The brute force method would involve a nested loop to check every pair of numbers, but the efficient way is to pass through the array only once, storing and checking complement values using a dictionary.

Here's an example of how you might write the code:

def two_sum(nums, target):
prevMap = {} # to store visited elements and their indices
for i, n in enumerate(nums):
diff = target - n
if diff in prevMap:
return [prevMap[diff], i]
prevMap[n] = i
return []

This function uses a hash map to find the complement of the current element in the array. If the complement is found, then the indices of the current element and its complement are returned.

User Hanan
by
5.6k points
4 votes

Answer:

def twoSum(nums, target):

for i in range(len(nums)):

for j in range(i+1, len(nums)):

if nums[i] + nums[j] == target:

return [i, j]

print(twoSum([2, 7, 11, 15], 9)) # should return [0, 1]

User Jeff McMahan
by
5.8k points