|
| 1 | +// Source : https://oj.leetcode.com/problems/two-sum/ |
| 2 | +// Author : Albin Zeng. |
| 3 | +// Date : 2017-02-26 |
| 4 | + |
| 5 | +/********************************************************************************** |
| 6 | +* |
| 7 | +* Given an array of integers, find two numbers such that they add up to a specific target number. |
| 8 | +* |
| 9 | +* The function twoSum should return indices of the two numbers such that they add up to the target, |
| 10 | +* where index1 must be less than index2. Please note that your returned answers (both index1 and index2) |
| 11 | +* are not zero-based. |
| 12 | +* |
| 13 | +* You may assume that each input would have exactly one solution. |
| 14 | +* |
| 15 | +* Input: numbers={2, 7, 11, 15}, target=9 |
| 16 | +* Output: index1=1, index2=2 |
| 17 | +* |
| 18 | +* |
| 19 | +**********************************************************************************/ |
| 20 | + |
| 21 | +/** |
| 22 | + *@param {number[]} nums |
| 23 | + *@param {number} target |
| 24 | + *@return {number[]} |
| 25 | + */ |
| 26 | +vartwoSum=function(nums,target){ |
| 27 | +constmap={}; |
| 28 | +leti=0; |
| 29 | +for(;i<nums.length;i++){ |
| 30 | +if(undefined===map[target-nums[i]]){ |
| 31 | +map[nums[i]]=i; |
| 32 | +}else{ |
| 33 | +return[map[target-nums[i]],i]; |
| 34 | +} |
| 35 | +} |
| 36 | +}; |