美文网首页
15. 三数之和

15. 三数之和

作者: 爱情小傻蛋 | 来源:发表于2019-08-07 17:59 被阅读0次

一、题目

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

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

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

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

二、解答

2.1方法一:双指针法
2.1.1 思路
  • 首先对数组进行排序,排序后固定一个数nums[i]nums[i],再使用左右指针指向nums[i]后面的两端,数字分别为nums[L]nums[L]和nums[R],计算三个数的和sum判断是否满足为 0,满足则添加进结果集
  • 如果nums[i]大于 0,则三数之和必然无法等于 0,结束循环
  • 如果nums[i] = nums[i-1],则说明该数字重复,会导致结果重复,所以应该跳过
  • 当sum = 0时,nums[L] = nums[L+1]则会导致结果重复,应该跳过,L++
  • 当sum =0 时,nums[R]= nums[R-1]则会导致结果重复,应该跳过,R--
  • 时间复杂度:O(n^2),n为数组长度
2.1.2 代码实现
public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        //数组大小小于3
        if (nums == null || nums.length < 3){
            return res;
        }
        //排序
        Arrays.sort(nums);

        int len = nums.length;

        for (int i = 0 ; i < len; i++){
            if (nums[i] > 0)
                break;

            //去重
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }

            int l = i + 1;
            int r = len - 1;
            while (l < r && r > 0){
                int sum = nums[i] + nums[l] + nums[r];

                if(sum == 0){
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[l]);
                    temp.add(nums[r]);
                    res.add(temp);

                    //去重
                    while (l < len-1 && nums[l] == nums[l+1]) l++;
                    while (r > 0 && nums[r] == nums[r-1]) r--;

                    r--;
                    l++;
                }else if (sum < 0){
                    l++;
                }else {
                    r--;
                }
            }
        }
        return res;
    }

相关文章

网友评论

      本文标题:15. 三数之和

      本文链接:https://www.haomeiwen.com/subject/iraodctx.html