-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.java
More file actions
34 lines (26 loc) · 867 Bytes
/
Copy pathtwoSum.java
File metadata and controls
34 lines (26 loc) · 867 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
package twoSum;
import java.util.HashMap;
import java.util.Map;
public class twoSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[]nums = new int[] {3, 2, 4};
int target = 6;
int[] result = twoSum(nums, target);
for (int i = 0; i < result.length; i++)
System.out.println("result: " + result[i]);
}
public static int[] twoSum(int[] nums, int target) {
Map <Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < nums.length;i++) {
int delta = target - nums[i];
if (!map.isEmpty() && map.containsKey(delta)) {
result = new int[]{map.get(delta), i};
return result;
}
map.put(nums[i], i);
}
return result;
}
}