Created
February 2, 2018 14:08
-
-
Save caglarorhan/77a53fb81ceb3404b86be8191fd172ad to your computer and use it in GitHub Desktop.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Given an array of integers, return indices of the two numbers such that they add up to a specific target. | |
You may assume that each input would have exactly one solution, and you may not use the same element twice. | |
Example: | |
Given nums = [2, 7, 11, 15], target = 9, | |
Because nums[0] + nums[1] = 2 + 7 = 9, | |
return [0, 1]. | |
* @param {number[]} nums | |
* @param {number} target | |
* @return {number[]} | |
*/ | |
var twoSum = function(nums, target) { | |
nums.forEach( | |
function(num1,index1){ | |
nums.forEach(function(num2,index2){ | |
if((index1!==index2) && num1+num2==target ){ | |
n = [index1,index2]; | |
return false; | |
} | |
}); | |
} | |
); | |
return n; | |
}; | |
console.log(twoSum([3,3],6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].