-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3sum.java
59 lines (47 loc) · 1.31 KB
/
3sum.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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
int a = i + 1;
int b = nums.length - 1;
int target = -nums[i];
if (target < 0) { // optimization. if our target is negative and the numbers to the right are all
// positive, finding a valid triplet is impossible. break the loop
break;
}
if (i > 0 && nums[i - 1] == nums[i]) { // avoids duplicate c
continue;
}
while (a < b) {
int sum = nums[a] + nums[b];
if (sum == target) {
List<Integer> triplet = new ArrayList<>();
triplet.add(-target);
triplet.add(nums[a]);
triplet.add(nums[b]);
ans.add(triplet);
a++;
while (a < b && nums[a - 1] == nums[a]) {
a++;
}
b--;
while (a < b && nums[b + 1] == nums[b]) {
b--;
}
} else if (sum > target) {
b--;
while (a < b && nums[b + 1] == nums[b]) {
b--;
}
} else {
a++;
while (a < b && nums[a - 1] == nums[a]) {
a++;
}
}
}
}
return ans;
}
}