Algorithms
two sum
seoca
2021. 3. 26. 23:34
function twoSum(numArr, target) {
//Create new Map
const numMap = new Map();
//Loop with index
for (const [index, element] of numArr.entries()) { //array iterator that returns key/value for each index.
//need to calculate the difference so we can compare with array elements
const diff = target - element
//If our numMap can find the current element which matches the diff, return the array
if (numMap.has(diff)) { //returns a boolean indicating whether an element with the specified key exists or not
return [numMap.get(diff), index] //
}
//Else add the diff of that element to numMap.
numMap.set(element, index) // lets you store unique values of any type
}
}
console.log(twoSum([6, 2, 3, 9, -5, 5, 7, 2], 9))