Created
July 20, 2020 23:21
-
-
Save cormac0108/aa4b40eef99baec0ae6bbb66bd4a2aec to your computer and use it in GitHub Desktop.
Question 2: Write a javascript function that takes an array of numbers and a target number. The function should find two different numbers in the array that, when added together, give the target number. For example: answer([1,2,3], 4)should return [1,3]
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
// Question 2: Write a javascript function that takes an array of numbers and a target number. The function should find | |
// two different numbers in the array that, when added together, give the target number. For example: answer([1,2,3], 4) | |
// should return [1,3] | |
function twoSumBest(array, target) { | |
const numsMap = new Map(); | |
for (let i = 0; i < array.length; i++) { | |
if(numsMap.has(target - array[i])) { | |
return [numsMap.get(target - array[i]), i]; | |
// get() returns a specified element associated with the specified key from the Map object. | |
} else { | |
numsMap.set(array[i], i); | |
// set() adds or updates an element with a specified key and value to a Map object. | |
} | |
} | |
} | |
console.time("Solution-4-Even more efficient solution"); | |
twoSumBest(arr, (arr[668] + arr[1669])); | |
console.timeEnd("Solution-4-Even more efficient solution"); | |
// Solution-4-Even more efficient solution: 0.103ms | |
// with thanks to https://rohan-paul.github.io/javascript/2018/04/29/2-sum/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment