-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (31 loc) · 972 Bytes
/
Copy pathSolution.java
File metadata and controls
33 lines (31 loc) · 972 Bytes
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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum > 0) {
k--;
} else if (sum < 0) {
j++;
} else {
int b = nums[j], c = nums[k];
result.add(List.of(nums[i], nums[j], nums[k]));
while(j < n && nums[j] == b) {
j++;
}
while(k >= 0 && nums[k] == c) {
k--;
}
}
}
}
return result;
}
}