Skip to content

Instantly share code, notes, and snippets.

@TechWithTy
Created September 27, 2020 02:49
Show Gist options
  • Save TechWithTy/31603ac44bf4d5cbd3b180140030b1d9 to your computer and use it in GitHub Desktop.
Save TechWithTy/31603ac44bf4d5cbd3b180140030b1d9 to your computer and use it in GitHub Desktop.
LeetCode Two Sum Problem
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
previousValues = {}; // Set Previous Hash Values
for (let i = 0; i < nums.length; i++){ // Loop through entire array
currentNum = nums[i]; // Get Current Loop Number
neededNum = target - currentNum; //Calculate Number Needed
index2 = previousValues[neededNum];// Check to see if number needed is in current hash table
if(index2 != null){ // If it is return index 2 and iteration number
return [index2,i];
}else{ // if it is Null save it in hash table
previousValues[currentNum] = i;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment