LeetCode-15-三数之和

本文介绍了一种寻找数组中三个数相加等于零的不重复组合的方法,并提供两种解决方案,一种时间复杂度较高(O(N^3)),另一种采用排序和双指针技巧,时间复杂度降低至O(N^2)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /*
        15.给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
        注意:答案中不可以包含重复的三元组
     */
    //方法一,个人解法正确,但是效率太低,时间复杂度O(N ^ 3),时间超时,无法提交至LeetCode
    public static List<List<Integer>> threeSum(int[] nums) {
        //int[] nums = {3,0,-2,-1,1,2,6,4,-3,8,-5,-9};
        //Arrays.sort(nums);
        List<Integer> integers = null;
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        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 (k < nums.length - 1 && nums[k] == nums[k + 1]) {
                        k++;
                        continue;
                    }
                    if (nums[i] + nums[j] + nums[k] == 0) {
                        integers = Arrays.asList( nums[i], nums[j], nums[k] );
                        Collections.sort( integers );
                        if (!res.contains( integers )) res.add( integers );
                        break;
                    }
                }
            }
        }
        return res;
    }

    //方法二,来源于LeetCode Discuss,很棒的解法,时间复杂度O(N ^ 2)
    public List<List<Integer>> threeSum2(int[] num) {
        Arrays.sort( num );
        List<List<Integer>> res = new LinkedList<>();
        int numLastIndex = num.length - 1;
        for (int i = 0; i < numLastIndex - 1; i++) {
            if (i == 0 || isCurrentDifferentFromPrevious( num, i )) {
                int lo = i + 1;
                int hi = numLastIndex;
                int sum = 0 - num[i];  // a + b = 0 - c
                while (lo < hi) {
                    if (num[lo] + num[hi] == sum) {
                        // found
                        res.add( Arrays.asList( num[i], num[lo], num[hi] ) );
                        while (lo < hi && num[lo] == num[lo + 1]) lo++; // dups on low index, move L index++
                        while (lo < hi && num[hi] == num[hi - 1]) hi--; // dups on high index, move H index--
                        // move indices to new positions with different values
                        lo++;
                        hi--;
                    } else if (num[lo] + num[hi] < sum) {
                        lo++;  // sum too small
                    } else {
                        hi--; // sum too large
                    }
                }
            }
        }
        return res;
    }

    private boolean isCurrentDifferentFromPrevious(int[] num, int i) {
        return i > 0 && num[i] != num[i - 1];
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值