Created
August 13, 2020 15:10
-
-
Save mitramejia/a034fbc91e476cd3aba57e4e4637b9f4 to your computer and use it in GitHub Desktop.
Two Sum
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
/** | |
* @param {number[]} nums | |
* @param {number} target | |
* @return {number[]} | |
*/ | |
var twoSum = function(nums, target) { | |
//hash table | |
var hash = {}; | |
for(let currentNumIndex=0; currentNumIndex <=nums.length; currentNumIndex++){ | |
//current number | |
var currentNumber = nums[currentNumIndex]; | |
console.log({currentNumber}) | |
//difference in the target and current number | |
var requiredNumber = target - currentNumber; | |
console.log({requiredNumber}) | |
// find the difference number from hashTable | |
const indexOfRequiredNumber = hash[requiredNumber]; | |
console.log({indexOfRequiredNumber}) | |
// if number found in hash, return index | |
// it will return undefined if not found | |
if(indexOfRequiredNumber != undefined) { | |
return [indexOfRequiredNumber, currentNumIndex] | |
} else { | |
// if not number found, we add the number into the hashTable | |
hash[currentNumber] = currentNumIndex; | |
} | |
console.log({hash}) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment