题目描述:

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:

[

[-1, 0, 1],

[-1, -1, 2]

]

解答代码:

  1. public class Unit15 {
  2. public static List<List<Integer>> threeSum(int[] nums) {
  3. Arrays.sort(nums);
  4. List<List<Integer>> result = new ArrayList<List<Integer>>();
  5. for (int i = 0; i < nums.length; i++) {
  6. // 右边全部大于0,没有判断的意义。
  7. if (nums[i] > 0) {
  8. break;
  9. }
  10. // 结果与上一次循环重复
  11. if (i > 0 && nums[i] == nums[i-1]) {
  12. continue;
  13. }
  14. int left = i + 1;
  15. int right = nums.length - 1;
  16. while (left < right) {
  17. int sum = nums[i] + nums[left] + nums[right];
  18. if (sum < 0) {
  19. left += 1;
  20. while (left < right && nums[left] == nums[left - 1]) {
  21. left += 1;
  22. }
  23. } else if (sum > 0) {
  24. right -= 1;
  25. while (left < right && nums[right] == nums[right + 1] ) {
  26. right -= 1;
  27. }
  28. } else {
  29. result.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));
  30. left += 1;
  31. right -= 1;
  32. while (left < right && nums[left] == nums[left - 1]) {
  33. left += 1;
  34. }
  35. while (left < right && nums[right] == nums[right + 1] ) {
  36. right -= 1;
  37. }
  38. }
  39. }
  40. }
  41. return result;
  42. }
  43. public static void main(String[] args) {
  44. int[] nums = new int[] {-2,0,1,1,2};
  45. // int[] nums = new int[] {-1, 0, 1, 2, -1, -4};
  46. List<List<Integer>> result = threeSum(nums);
  47. for (List<Integer> list : result) {
  48. System.out.println(list.toString());
  49. }
  50. }
  51. }

解答思路:

1.排序(必须排序,不然没得执行)
2.遍历
3.从第一个节点开始,左边第一个(当前节点的右边第一个)是左节点,最后一个节点是右节点。
左右节点相加与当前节点和为0,则追加到集合中。
4.判断的过程中,sum < 0,左节点移动到下一位(右移)。sum > 0,右节点移动到下一位(左移)。