-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtwo_sum.java
More file actions
30 lines (28 loc) · 837 Bytes
/
Copy pathtwo_sum.java
File metadata and controls
30 lines (28 loc) · 837 Bytes
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
28
29
30
import java.util.HashMap;
import java.util.Map;
/**
* Created by codingBoy on 17/2/3.
*/
public class two_sum {
public static void main(String[] args)
{
int[] numbers=new int[]{2,7,11,15};
int target=9;
int[] result =new int[2];
result=twoSum(numbers,target);
System.out.println(result[0]+","+result[1]);
}
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
}