1. 题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/d590ef10469e4f9190a64a563f95b0b8.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6Zi_6LSi57un57ut5Yqq5Yqb,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
2. 思路
(1) 双指针法
- 首先对数组进行快速排序,然后遍历数组,确定a值后,利用双指针法从后面数组的两端开始往中间移动,找到使a+b+c=0的元素。
- 注意找到后不能直接返回,中间可能还有其他答案,需要继续移动。
3. 代码
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
int n = num.length;
if (n < 3) {
return res;
}
Arrays.sort(num);
for (int i = 0; i < n; i++) {
if (i > 0 && num[i] == num[i - 1]) {
continue;
}
int left = i + 1;
int right = n - 1;
while (left < right) {
if (num[i] + num[left] + num[right] == 0) {
res.add(new ArrayList<>(Arrays.asList(num[i], num[left], num[right])));
int l = num[left];
while (left < n && num[left] == l) {
left++;
}
int r = num[right];
while (right >= 0 && num[right] == r) {
right--;
}
} else if (num[i] + num[left] + num[right] > 0) {
right--;
} else {
left++;
}
}
}
return res;
}
}