-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day-8 3Sum
40 lines (39 loc) · 1.56 KB
/
Day-8 3Sum
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
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 > i + 1 && nums[lo] == nums[lo - 1]))
++lo;
else if (sum > 0 || (hi < nums.length - 1 && nums[hi] == nums[hi + 1]))
--hi;
else
res.add(Arrays.asList(nums[i], nums[lo++], nums[hi--]));
}
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Set<Pair> found = 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) {
int v1 = Math.min(nums[i], Math.min(complement, nums[j]));
int v2 = Math.max(nums[i], Math.max(complement, nums[j]));
if (found.add(new Pair(v1, v2)))
res.add(Arrays.asList(nums[i], complement, nums[j]));
}
seen.put(nums[j], i);
}
return res;
}