一、题目内容

image.png

二、题解

解法1:

思路

image.png

代码

  1. public class Solution {
  2. public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
  3. ArrayList<ArrayList<Integer>> res = new ArrayList<>();
  4. if (num == null || num.length < 3) {
  5. return res;
  6. }
  7. // 对数组从小到大排序
  8. Arrays.sort(num);
  9. int length = num.length;
  10. for (int k = 0; k < length; k++) {
  11. // 如果相邻的两个元素相等,则直接跳过,防止重复
  12. if (k > 0 && num[k] == num[k - 1]) {
  13. continue;
  14. }
  15. // right 是右侧指针
  16. int right = length - 1;
  17. int temp = -num[k];
  18. // 从第一个元素后边开始遍历
  19. for (int left = k + 1; left < length; left++) {
  20. if (left > k + 1 && num[left] == num[left - 1]) {
  21. continue;
  22. }
  23. while (right > left && num[right] + num[left] > temp) {
  24. right--;
  25. }
  26. if (left == right) {
  27. break;
  28. }
  29. if (num[left] + num[right] == temp) {
  30. ArrayList<Integer> list = new ArrayList<Integer>();
  31. list.add(num[k]);
  32. list.add(num[left]);
  33. list.add(num[right]);
  34. res.add(list);
  35. }
  36. }
  37. }
  38. return res;
  39. }
  40. }