Last active
April 14, 2021 12:28
-
-
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
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
/** | |
* 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