Directions
If you have an array of integers, the task is to find the indices of two numbers that add up to a specific target.
There will be exactly one solution for each input, and you cannot use the same element twice.
For Example
Given nums = [2, 7, 11, 15], target = 9,
Since nums[0] + nums[1] = 2 + 7 = 9, you should return [0, 1].
Is there a way to achieve this without using nested for-loops? I want to lower the time complexity.
Sample Code
const twoSum = function(nums, target) {
for(let i in nums){
for(let j in nums) {
if(nums[i] + nums[j] === target && nums[i] != nums[j]) {
return [i, j];
}
}
}
};
console.log(twoSum([2, 7, 11, 15], 9));