-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
40 lines (32 loc) · 979 Bytes
/
Copy pathTwoSum.java
File metadata and controls
40 lines (32 loc) · 979 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
package leetcode;
import java.util.HashMap;
import java.util.Scanner;
/**
* Created by helmeter on 6/11/16.
*/
public class TwoSum {
public static int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> nums = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; ++i) {
// add i-th number
Integer a = nums.get(numbers[i]);
if (a == null)
nums.put(numbers[i], i);
// find (target - numbers[i])
a = nums.get(target - numbers[i]);
if (a != null && a < i) {
res[0] = a + 1;
res[1] = i + 1;
break;
}
}
return res;
}
public static void main(String[] args) {
int[] numbers ={2,12,3,5,2,3};
int target = 4;
int[] res = twoSum(numbers, target);
System.out.println(res[0] + " " + res[1]);
}
}