-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwoSum.java
78 lines (72 loc) · 2.11 KB
/
TwoSum.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package dsalgo.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* TwoSum
* Find indices of the two numbers such that they add up to a specific target
*
* @author Umang G
*/
public class TwoSum {
/**
* <p>
* {@code TwoSum} instance should NOT be constructed in standard
* programming, so its defined as private
* </p>
*/
private TwoSum() {
}
/**
* twoSumOnePassHashTable
*
* @param nums array elements
* @param target target value
* @return array of two indices
*/
public static int[] twoSumOnePassHashTable(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int index = 0; index < nums.length; index++) {
if (map.containsKey(nums[index])) {
return new int[] { map.get(nums[index]), index };
} else {
map.put(target - nums[index], index);
}
}
return new int[] { -1, -1 };
}
/**
* twoSumTwoPassHashTable
*
* @param nums array elements
* @param target target value
* @return array of two indices
*/
public static int[] twoSumTwoPassHashTable(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
return new int[] { -1, -1 };
}
/**
* twoSumBruteForce
*
* @param nums array elements
* @param target target value
* @return array of two indices
*/
public static int[] twoSumBruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
for (int j = i + 1; j < nums.length; j++)
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
return new int[] { -1, -1 };
}
}