-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum.java
More file actions
55 lines (43 loc) · 1.5 KB
/
ThreeSum.java
File metadata and controls
55 lines (43 loc) · 1.5 KB
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
// Sort the array
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// Skip duplicate elements for i
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
// Found a triplet with zero sum
ans.add(Arrays.asList(nums[i], nums[j], nums[k]));
// Skip duplicate elements for j
while (j < k && nums[j] == nums[j + 1]) {
j++;
}
// Skip duplicate elements for k
while (j < k && nums[k] == nums[k - 1]) {
k--;
}
// Move the pointers
j++;
k--;
} else if (sum < 0) {
// Sum is less than zero, increment j to increase the sum
j++;
} else {
// Sum is greater than zero, decrement k to decrease the sum
k--;
}
}
}
return ans;
}
}