Created
October 18, 2017 04:36
-
-
Save mnicole/2cb3686e101d7827273eb7479ff7cc05 to your computer and use it in GitHub Desktop.
function to check for the position of 2 numbers that equal a certain sum
This file contains 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
/** | |
* Function to check for the position of 2 numbers that equal a certain sum. Only one pair per array. | |
* @param {number[]} nums | |
* @param {number} target | |
* @return {number[]} | |
*/ | |
const twoSum = function(nums, target) { | |
let checked = {}, | |
found; | |
nums.forEach((n, index) => { | |
if (found) return; | |
const complement = target - n; | |
if (checked[complement]) { | |
found = [checked[complement].position, index]; | |
} | |
else { | |
checked[n] = { position: index }; | |
} | |
}) | |
return found; | |
}; | |
const nums = [ 1, 3, 2, 9, 4, 8]; | |
const target = 6; | |
const findPosition = twoSum(nums, target); | |
console.log(findPosition); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment