Last active
July 10, 2024 03:24
-
-
Save nodahikaru/532e5f6c2f11316da22625e703eac69e to your computer and use it in GitHub Desktop.
Target Sum Javascript
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
function twoSum(nums, target) { | |
// Create a map to store each number and its index | |
const numMap = new Map(); | |
// Iterate through the array | |
for (let i = 0; i < nums.length; i++) { | |
const complement = target - nums[i]; | |
// Check if the complement exists in the map | |
if (numMap.has(complement)) { | |
// Return the pair (complement, current number) | |
return [complement, nums[i]]; | |
} | |
// Store the current number and its index in the map | |
numMap.set(nums[i], i); | |
} | |
// Return null if no such pair is found | |
return null; | |
} | |
// Example usage | |
const nums = [2, 7, 11, 15]; | |
const target = 9; | |
const result = twoSum(nums, target); | |
console.log(result); // Output: [2, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment