Original:LeetCode – Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target number.Note: both index1 and index2 are not zero-based.
For example:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;
public class TestTwoSum{
public static void main(String[] args){
int[] numbers = {2, 5, 9, 6, 4, 3};
int target = 10;
HashSet<Integer> result = TwoSum(numbers, target);
System.out.println(result);
}
public static HashSet<Integer> TwoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
HashSet<Integer> result = new HashSet<Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
result.add(map.get(numbers[i]) + 1);
result.add(i + 1);
break;
} else
map.put(target - numbers[i], i);
}
return result;
}
}
1
[4, 5]