|
| 1 | +# JavaScript Two Sum |
| 2 | + |
| 3 | +## Challenge: |
| 4 | + |
| 5 | +Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. |
| 6 | + |
| 7 | +You may assume that each input would have exactly one solution, and you may not use the same element twice. |
| 8 | + |
| 9 | +You can return the answer in any order. |
| 10 | + |
| 11 | +### 1<sup>st</sup> Example: |
| 12 | + |
| 13 | +`Input: nums = [2,7,11,15], target = 9` |
| 14 | +<br/> |
| 15 | +`Output: [0,1]` |
| 16 | +<br/> |
| 17 | +`Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].` |
| 18 | + |
| 19 | +### 2<sup>nd</sup> Example: |
| 20 | + |
| 21 | +`Input: nums = [3,2,4], target = 6` |
| 22 | +<br/> |
| 23 | +`Output: [1,2]` |
| 24 | + |
| 25 | +### 3<sup>rd</sup> Example: |
| 26 | + |
| 27 | +`Input: nums = [3,3], target = 6` |
| 28 | +<br/> |
| 29 | +`Output: [0,1]` |
| 30 | + |
| 31 | +### Constraints: |
| 32 | + |
| 33 | +`2 <= nums.length <= 10⁴` |
| 34 | +<br/> |
| 35 | +`-10⁹ <= nums[i] <= 10⁹` |
| 36 | +<br/> |
| 37 | +`-10⁹ <= target <= 10⁹` |
| 38 | +<br/> |
| 39 | +Only one valid answer exists. |
| 40 | + |
| 41 | +## Solution: |
| 42 | + |
| 43 | +`const twoSum = (nums, target) => {` |
| 44 | +<br/> |
| 45 | + `let numsObject = {};` |
| 46 | +<br/> |
| 47 | +<br/> |
| 48 | + `for(let i = 0; i < nums.length; i++) {` |
| 49 | +<br/> |
| 50 | + `let n = nums[i],` |
| 51 | +<br/> |
| 52 | + `compliment = target-n;` |
| 53 | +<br/> |
| 54 | +<br/> |
| 55 | + `if (numsObject.hasOwnProperty(compliment)) {` |
| 56 | +<br/> |
| 57 | + `return [i,numsObject[compliment]];` |
| 58 | +<br/> |
| 59 | + `}` |
| 60 | +<br/> |
| 61 | +<br/> |
| 62 | + `numsObject[n] = i;` |
| 63 | +<br/> |
| 64 | + `}` |
| 65 | +<br/> |
| 66 | +<br/> |
| 67 | + `return [-1,-1];` |
| 68 | +<br/> |
| 69 | +`};` |
| 70 | +<br/> |
| 71 | +<br/> |
0 commit comments