每日一道算法题LeetCode15:3Sum(三数之和)

三数之和

  • 题目
  • 分析
  • 题解
    • 暴力法
    • 双指针
  • 总结

题目

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

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

分析

这个题实际上有两个要求,首先要找到三个数和为0,其次不包含重复的三元组,其实我倒觉得第一个要求并不难,去重反而较为麻烦

题解

暴力法

对于这种题,暴力法永远都是可以完成的,要有三个数的和为0?那就三重循环呗。可是,当用到了三重循环,一般LeetCode都是超时,这题也是这样,压根过不了。

public static List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> result = new LinkedHashSet<>();
        Arrays.sort(nums);     // 先排序,再利用Set去重
        for (int i = 0; i < nums.length-2; i++) {
            for (int j = i+1; j < nums.length-1; j++) {
                for (int k = j+1; k < nums.length; k++) {
                    if(nums[i]+nums[j]+nums[k] == 0){
                        result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    }
                }
            }
        }
        return new ArrayList<>(result);
    }

双指针

暴力解决不了,想了一下没啥思路,看一下题目标签,双指针,有思路了,就有了如下代码:

    public static List<List<Integer>> threeSum(int[] nums){
		List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        if(len<3) return res;
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if(nums[i] > 0)   break;  // 按照升序排列,当i>0时,不可能凑0
            else if(i>=1 && nums[i] == nums[i-1])    continue;  // 去重,本数和上一个数相同,直接跳过
            int L = i+1,R = len-1;   //左右指针
            while(R > L){
                int sum = nums[i] + nums[L] + nums[R];
                if(sum == 0){
                    res.add(Arrays.asList(nums[i] , nums[L] , nums[R]));
                    while (L<R && nums[L] == nums[L+1]) L++; // 去重
                    while (L<R && nums[R] == nums[R-1]) R--; // 去重
                    L++;
                    R--;
                }
                else if(sum<0) L++;   // sum比0小,L往右移动,加大
                else R--;   // sum比0大,R往左移,减小
            }
        }
        return res;
    }

总结

其实这个题还有很多其他解法,比如使用hashmap,看完之后只能给跪了,大家可以多看看其他题解,我这里就写这两个最好理解的方法了。

你可能感兴趣的:(每日一道算法题LeetCode15:3Sum(三数之和))