-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.java
More file actions
33 lines (27 loc) · 929 Bytes
/
twoSum.java
File metadata and controls
33 lines (27 loc) · 929 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
import java.util.HashMap;
public class twoSum {
public int[] twoSum(int[] nums, int target) {
Integer n = nums.length;
int[] result = new int[2];
//method 1:two loop
for (Integer i = 0; i < n; i++) {
for (Integer j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
}
}
}
//method 2 hashmap
HashMap<Integer, Integer> Index = new HashMap<Integer, Integer>();
for (Integer i = 0; i < nums.length; i++) {
Integer targetKey=target-nums[i];
if (Index.containsKey(targetKey)) {
result[0] = i;
result[1] = Index.get(targetKey);
}
Index.put(nums[i],i);
}
return result;
}
}