-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm15.java
More file actions
37 lines (36 loc) · 1.11 KB
/
prblm15.java
File metadata and controls
37 lines (36 loc) · 1.11 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
import java.util.*;
public class prblm15 {
public static void main(String[] args) {
int[] nums = {-1,0,1,2,-1,-4};
System.out.println(threeSum(nums));
}
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = n - 1;
while (j < k) {
int x = nums[i] + nums[j] + nums[k];
if (x < 0) {
j++;
} else if (x > 0) {
k--;
} else {
ans.add(List.of(nums[i], nums[j++], nums[k--]));
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
}
}
}
return ans;
}
}