Skip to content

Instantly share code, notes, and snippets.

@YasuhiroYoshida
Last active April 14, 2021 12:28
Show Gist options
  • Save YasuhiroYoshida/b6fd97b20b38770fd8d7734a8cc7b55b to your computer and use it in GitHub Desktop.
Save YasuhiroYoshida/b6fd97b20b38770fd8d7734a8cc7b55b to your computer and use it in GitHub Desktop.
LeetCode: Two Sum (https://leetcode.com/problems/two-sum/) submitted and accepted at 2021-03-26 20:56
/**
* LeetCode
* Two Sum (https://leetcode.com/problems/two-sum/)
*
* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
*
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
*
* You can return the answer in any order.
*
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function(nums, target) {
let complements = [];
for (let i = 0; i < nums.length; i++) {
let complementAt = complements.indexOf(nums[i]);
if (complementAt > -1) {
return [complementAt, i];
}
let complement = target - nums[i];
complements.push(complement);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment