类似于力扣:15. 三数之和
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (num == null || num.length < 3) return res;
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
if (num[i] > 0) return res;
if (i > 0 && num[i] == num[i - 1]) continue;
int l = i + 1;
int r = num.length - 1;
while (l < r) {
int sum = num[i] + num[l] + num[r];
if (sum == 0) {
//强制转换类型
res.add(new ArrayList<>(Arrays.asList(num[i], num[l], num[r])));
while (l < r && num[l] == num[l + 1]) l++;
while (l < r && num[r] == num[r - 1]) r--;
l++;
r--;
}
else if (sum < 0) l++;
else if (sum > 0) r--;
}
}
return res;
}
}