Problem Description#
Given an integer array nums
and an integer target, please find two integers in the array that add up to the target value, and return their indices in the array.
You can assume that each input will have only one solution. However, the same element in the array cannot appear twice in the answer.
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]
Note:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
There will only be one valid answer.
Approach#
- The problem guarantees that there is only one valid answer, so we can return the result as soon as we find a solution during the iteration.
- While iterating through the array and inserting elements into the map, we also check if the target element corresponding to the current element already exists in the map.
- If it exists, we have found the solution and immediately return the indices.
Solution#
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const m = new Map();
const len = nums.length;
for (let i = 0; i < len; i++) {
if (m.has(target - nums[i])) {
return [i, m.get(target - nums[i])];
}
m.set(nums[i], i);
}
return [];
};