|
| 1 | +packageAlgorithms.sequence; |
| 2 | + |
| 3 | +importjava.util.HashMap; |
| 4 | + |
| 5 | +/* |
| 6 | + * Two Sum Total Accepted: 36938 Total Submissions: 200732 My Submissions Question Solution |
| 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, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. |
| 10 | +
|
| 11 | +You may assume that each input would have exactly one solution. |
| 12 | +
|
| 13 | +Input: numbers={2, 7, 11, 15}, target=9 |
| 14 | +Output: index1=1, index2=2 |
| 15 | + * */ |
| 16 | + |
| 17 | +publicclassTwoSum { |
| 18 | +publicint[]twoSum(int[]numbers,inttarget) { |
| 19 | +HashMap<Integer,Integer>map =newHashMap<Integer,Integer>(); |
| 20 | +int[]ret =newint[2]; |
| 21 | + |
| 22 | +for (inti =0;i <numbers.length;i++) { |
| 23 | +if (map.containsKey(target -numbers[i])) { |
| 24 | + |
| 25 | +// As the index is not ZERO based, we should add one to the result. |
| 26 | +ret[0] =map.get(target -numbers[i]) +1; |
| 27 | +ret[1] =i +1; |
| 28 | +returnret; |
| 29 | + } |
| 30 | +map.put(numbers[i],i); |
| 31 | + } |
| 32 | + |
| 33 | +returnret; |
| 34 | + } |
| 35 | +} |