Created
October 26, 2024 18:21
-
-
Save sAVItar02/a2bd53e402b02afb7b517ac4fb68226c 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) { | |
let map = new Map(); | |
for(let i=0; i<nums.length; i++) { | |
let numToFind = target - nums[i]; | |
if(map.has(numToFind)) return [map.get(numToFind), i]; | |
else map.set(nums[i], i); | |
} | |
return null | |
}; | |
// Store the elements in a hashmap | |
// Start traversing the array and find (target - element at current iteration) | |
// If the map has the item needed, then return the current iteration value and the value found | |
// If not then add the value to the map and move on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment