Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created October 13, 2022 12:53
Show Gist options
  • Save trafficinc/42624ba6c3b438e753a9850d0f234d05 to your computer and use it in GitHub Desktop.
Save trafficinc/42624ba6c3b438e753a9850d0f234d05 to your computer and use it in GitHub Desktop.
Leetcode - Two Sum Solution
/*
Two Sum
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
*/
let twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
map.set(nums[i], i);
}
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i];
if (map.has(complement) && map.get(complement) !== i) {
return [i, map.get(complement)];
}
}
return null;
};
console.log(twoSum([2, 7, 11, 15], 9));
console.log(twoSum([3, 2, 4], 6));
console.log(twoSum([3, 3], 6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment