-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
43 lines (39 loc) · 924 Bytes
/
Copy pathTwoSum.java
File metadata and controls
43 lines (39 loc) · 924 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
31
32
33
34
35
36
37
38
39
40
41
42
43
package Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TwoSum
{
public int[] twoSum(int[] numbers, int target)
{
Map<Integer, Integer> process = new HashMap<Integer, Integer>();
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < numbers.length; i++)
{
int numToFind = target - numbers[i];
if (process.containsKey(numToFind))
{
result.add(process.get(numToFind));
result.add(i);
}
process.put(numbers[i], i);
}
int re[] = new int[result.size()];
for (int i = 0; i < result.size(); i++)
{
re[i] = result.get(i).intValue() + 1;
}
return re;
}
public static void main(String[] args)
{
TwoSum toSum = new TwoSum();
int numbers[] = {2,7,13,43};
int result[] = toSum.twoSum(numbers, 9);
for (int i = 0; i < result.length; i++)
{
System.out.println(result[i]+1);
}
}
}