-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTwoSumAllPairs.java
30 lines (27 loc) · 1.01 KB
/
TwoSumAllPairs.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
package algorithm.pointers.twosum;
import java.util.*;
/**
* Find all pairs of elements in a given array that sum to the given target number.
* Return all the pairs of indices.
*/
public class TwoSumAllPairs {
// HashMap: Time O(n), Space O(n)
public List<List<Integer>> twoSumAllPairs(int[] array, int target) {
List<List<Integer>> res = new ArrayList<>();
Map<Integer, List<Integer>> visited = new HashMap<>();
// key = number, value = list of indices
for (int i = 0; i < array.length; i++) {
int diff = target - array[i];
List<Integer> indices = visited.get(diff);
if (indices != null) {
// enumerate all possible indices pairs of current (array[i], diff) pair
for (int idx : indices) {
res.add(Arrays.asList(i, idx));
}
}
visited.putIfAbsent(array[i], new ArrayList<>());
visited.get(array[i]).add(i);
}
return res;
}
}