Skip to content

Instantly share code, notes, and snippets.

@DuncanMcArdle
Last active October 29, 2020 14:30
LeetCode problem 1 blog - Map
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