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.
Cpp Program Code:
The twoSum function takes as input a vector of integers nums and an integer target. It then initializes an empty unordered map numToIndex to keep track of the indices of the numbers in nums. It then loops through each element nums[i] in nums. For each nums[i], it computes the complement target - nums[i]. If the complement is already in the numToIndex map, it means that we have found a pair of numbers that add up to target. We return the indices of the complement and the current nums[i] in the form of a vector. Otherwise, we add the current nums[i] and its index i to the numToIndex map.
In the main function, we create an example input nums = {2, 7, 11, 15} and target = 9. We then call the twoSum function with these inputs and store the result in result. Finally, we print the result in the format [i, j] using cout.
Python Program code:
The twoSum function takes as input a list of integers nums and an integer target. It then initializes an empty dictionary numToIndex to keep track of the indices of the numbers in nums. It then loops through each element num and its index i in nums. For each num, it computes the complement target - num. If the complement is already in the numToIndex dictionary, it means that we have found a pair of numbers that add up to target. We return the indices of the complement and the current num in the form of a list. Otherwise, we add the current num and its index i to the numToIndex dictionary.
In the main code block, we create an example input nums = [2, 7, 11, 15] and target = 9. We then call the twoSum function with these inputs and store the result in result. Finally, we print the result using print.