Last active
October 29, 2020 14:30
LeetCode problem 1 blog - Map
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
var twoSum = function (nums, target) { | |
// Initialise a map to store the first run of numbers | |
const mapOfNumbers = new Map(); | |
// Loop through the numbers | |
for (var i = 0; i < nums.length; i++) { | |
// Determine the complement (required number) for the current number | |
const complement = target - nums[i]; | |
// Check if the complement exists in the Map | |
if (mapOfNumbers.has(complement)) { | |
return [mapOfNumbers.get(complement), i]; | |
} | |
// If not, add the current number to the Map | |
mapOfNumbers.set(nums[i], i); | |
} | |
}; | |
console.log(twoSum([2, 7, 11, 15], 9)); // Outputs: [0, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment