-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum.java
More file actions
41 lines (34 loc) · 1.16 KB
/
ThreeSum.java
File metadata and controls
41 lines (34 loc) · 1.16 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
import java.util.*;
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int l, r;
Set<List<Integer>> result = new HashSet<>();
for (int i = 0; i < nums.length - 2; i++) {
l = i + 1;
r = nums.length - 1;
while (l < r) {
// System.out.println(nums[i] + " " + nums[l] + " " + nums[r]);
if (nums[i] + nums[l] + nums[r] == 0) {
List<Integer> newList = new ArrayList<>();
newList.add(nums[i]);
newList.add(nums[l]);
newList.add(nums[r]);
result.add(newList);
l++;
} else if (nums[i] + nums[l] + nums[r] < 0) {
l++;
} else {
r--;
}
}
}
List<List<Integer>> finalList = new ArrayList<>(result);
return finalList;
}
public static void main(String[] args) {
ThreeSum threeSum = new ThreeSum();
int[] n = {0, 0, 0, 0};
System.out.println(threeSum.threeSum(n));
}
}