-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
39 lines (33 loc) · 1.04 KB
/
TwoSum.java
File metadata and controls
39 lines (33 loc) · 1.04 KB
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
package algorithm.dp;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
int[] arr = {3,2,4};
twoSum(arr, 6);
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> duplicationMap = new HashMap();
Map<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) != null) {
duplicationMap.put(nums[i], i);
} else {
map.put(nums[i], i);
}
}
for (int i = 0; i < nums.length; i++) {
if (target % nums[i] == 0) {
Integer delta = duplicationMap.get(target - nums[i]);
if (delta != null) {
return new int[]{i, delta};
}
}
Integer delta = map.get(target - nums[i]);
if (delta != null) {
return new int[]{i, delta};
}
}
return new int[] {0, 0};
}
}