Two Sum
Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target .
##For Example
console.log(twoSum([1, 6, 4, 5, 3, 3], 7)); => [ [ 6, 1 ], [ 3, 4 ], [ 3, 4 ] ] console.log(twoSum([40, 11, 19, 17, -12], 28)); => [ [ 17, 11 ], [ -12, 40 ] ]##
function twoSum(numArray, sum) {
var pairs = [];
var hashtable = [];
for (var i = 0; i < numArray.length; i++) {
var currNum = numArray[i];
var counterpart = sum - currNum;
if (hashtable.indexOf(counterpart) !== -1) {
pairs.push([currNum, counterpart])
}
hashtable.push(currNum)
}
return pairs;
}
console.log(twoSum([1, 6, 4, 5, 3, 3], 7));
console.log(twoSum([40, 11, 19, 17, -12], 28));
Two Build our two sum algorithm we start by defining a function called twoSum this
function will have two arguments an array and a sum
The first thing we want to do to create an an array called pairs. Next we want to create a loop
that will iterate in our argument called numArray.
We will define the current number by saying var currNum = numArray[i] at position i.
What we want to do is to create a hashtable and create a variable hashtable to store our numbers.
We have our current number now we have to define our counterpart by createing variable counterpart that is the sum - currNum;
Now we have to check our hashtable to see if our couterpart exist in it.
We create if statement if hashtable indexOf couterpart is true or is different of -1;
We push into pairs the currNum and counterpart
Outside of our if statement we need to push into our hashtable by pushing the currNum
In the end we return the pairs.