-
Notifications
You must be signed in to change notification settings - Fork 43
/
ThreeSum.java
86 lines (78 loc) · 2.79 KB
/
ThreeSum.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
79
80
81
82
83
84
85
86
package LeetCodeJava.Array;
// https://leetcode.com/problems/3sum/
import java.util.*;
public class ThreeSum {
// V0
// V1
// IDEA : Two Pointers
// https://leetcode.com/problems/3sum/editorial/
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length && nums[i] <= 0; ++i)
if (i == 0 || nums[i - 1] != nums[i]) {
twoSumII(nums, i, res);
}
return res;
}
void twoSumII(int[] nums, int i, List<List<Integer>> res) {
int lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
if (sum < 0) {
++lo;
} else if (sum > 0) {
--hi;
} else {
res.add(Arrays.asList(nums[i], nums[lo++], nums[hi--]));
while (lo < hi && nums[lo] == nums[lo - 1])
++lo;
}
}
}
// V2
// IDEA: HASH SET
// https://leetcode.com/problems/3sum/editorial/
public List<List<Integer>> threeSum_2(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length && nums[i] <= 0; ++i)
if (i == 0 || nums[i - 1] != nums[i]) {
twoSum(nums, i, res);
}
return res;
}
void twoSum(int[] nums, int i, List<List<Integer>> res) {
HashSet<Integer> seen = new HashSet<Integer>();
for (int j = i + 1; j < nums.length; ++j) {
int complement = -nums[i] - nums[j];
if (seen.contains(complement)) {
res.add(Arrays.asList(nums[i], nums[j], complement));
while (j + 1 < nums.length && nums[j] == nums[j + 1])
++j;
}
seen.add(nums[j]);
}
}
// V3
// IDEA : "No-Sort"
// https://leetcode.com/problems/3sum/editorial/
public List<List<Integer>> threeSum_3(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
Set<Integer> dups = new HashSet<>();
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; ++i)
if (dups.add(nums[i])) {
for (int j = i + 1; j < nums.length; ++j) {
int complement = -nums[i] - nums[j];
if (seen.containsKey(complement) && seen.get(complement) == i) {
List<Integer> triplet = Arrays.asList(nums[i], nums[j], complement);
Collections.sort(triplet);
res.add(triplet);
}
seen.put(nums[j], i);
}
}
return new ArrayList(res);
}
}