-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThreeSUM.java
56 lines (28 loc) · 970 Bytes
/
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
import java.util.*;
public class ThreeSUM {
public static List<int[]> getTripletSumZero(int[] nums) {
List<int[]> triplets = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int a = nums[i], start = i + 1, end = nums.length - 1;
while (start < end) {
int b = nums[start], c = nums[end];
if (a + b + c >= 0) {
if (a + b + c == 0) {
triplets.add(new int[]{a, b, c});
}
end--;
} else {
start++;
}
}
}
return triplets;
}
public static void main(String[] args) {
int[] nums = new int[]{-25, -10, -7, -3, 2, 4, 8, 10};
for (int[] triplet : getTripletSumZero(nums)) {
System.out.println(Arrays.toString(triplet));
}
}
}