Created
September 27, 2020 02:49
-
-
Save TechWithTy/31603ac44bf4d5cbd3b180140030b1d9 to your computer and use it in GitHub Desktop.
LeetCode Two Sum Problem
This file contains hidden or 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
/** | |
* @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