-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution15.java
46 lines (39 loc) · 1.33 KB
/
Solution15.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
package leetcode.doublepointer;
import java.util.*;
public class Solution15 {
public static void main(String[] args) {
System.out.println(new Solution15().threeSum(new int[]{-1, -1, 0, 1, 2}));
}
public List<List<Integer>> threeSum(int[] nums) {
// 排序
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) {
i++;
}
if (i >= nums.length) {
break;
}
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
} else if (sum < 0) {
left++;
} else {
right--;
}
while (left > i + 1 && left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && right < nums.length - 1 && nums[right] == nums[right + 1]) {
right--;
}
}
}
return res;
}
}