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; } int n = num.length; Arrays.sort(num); for (int i = 0; i < n - 2; i++) { if (i > 0 && num[i] == num[i - 1]) { continue; } int left = i + 1; int right = n - 1; while (left < right) { int sum = num[i] + num[left] + num[right]; if (sum == 0) { ArrayList<Integer> list = new ArrayList<>(); list.add(num[i]); list.add(num[left]); list.add(num[right]); res.add(list); int tmp = num[left]; while (left < right && num[left] == tmp) { left++; } tmp = num[right]; while (left < right && num[right] == tmp) { right--; } } else if (sum < 0) { left++; } else { right--; } } } return res; } }