三数之和

问题描述

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

注意:答案中不可以包含重复的三元组。

实例:

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

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解:

思路:

  • 标签:数组遍历;
  • 首先对数组进行排序,排序后固定一个数 nums[i],再使用左右指针指向 nums[i]后面的两端,数字分别为 nums[low] 和 nums[high],计算三个数的和 sum 判断是否满足为 00,满足则添加进结果集;

  • 如果 nums[i]大于 0,则三数之和必然无法等于 0,结束循环;
  • 如果 nums[i] == nums[i-1],则说明该数字重复,会导致结果重复,所以应该跳过;
  • 当 sum = 0时,nums[low] == nums[low+1] 则会导致结果重复,应该跳过,low++;
  • 当 sum = 0 时,nums[high]== nums[high-1] 则会导致结果重复,应该跳过,high--;
  • 时间复杂度:O(n^2)n 为数组长度

代码如下:

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if (nums == null || nums.length < 3) return ans;
        //对数组排序,为了二分查找
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            //如果大于0,证明相加不可能等于0
            if (nums[i] > 0) break;
            //num[i] == num[i-1] 为了防止重复
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            //
            int low = i + 1, high = nums.length - 1;
            while (low < high) {
                int sum =nums[i] + nums[low] + nums[high];
                if ( sum == 0) {
                    ans.add(Arrays.asList(nums[i], nums[low], nums[high]));
                    while (low < high && nums[low] == nums[low + 1]) low++;
                    while (low < high && nums[high] == nums[high - 1]) high--;
                    low++;
                    high--;
                } else if (sum < 0) {
                    low++;
                } else {
                    high--;
                }
            }
        }
        return ans;
    }
原文地址:https://www.cnblogs.com/xiaofeng-fu/p/13970079.html