15. 3Sum

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

note:先将数组排序,复杂度为Log(n),从两边往中间找,复杂度为Log(n^{2}),在找的过程中要注意去重,分别有两次去重,第一次在进入循环找数之前,第二次在找到数之后,begin右移,end左移,再次比较begin和end的数是否与前一步的数值相等,如若相等,则再次移动

public static List<List<Integer>> threeSum(int[] nums) {
        /**
         * 优化过后的算法
         */
        List<List<Integer>> ret = new ArrayList<>();
        if (nums == null || nums.length < 3) return ret;
        int len = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            // 减少无意义的循环
            if (nums[i] > 0) break;
            // 避免重复
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int begin = i + 1;
            int end = len - 1;
            while (begin < end) {
                int sum = nums[i] + nums[begin] + nums[end];
                if (sum == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[begin]);
                    list.add(nums[end]);
                    ret.add(list);
                    begin++;
                    end--;
                    // 避免重复
                    while (begin < end && nums[begin] == nums[begin - 1])
                        begin++;
                    while (begin < end && nums[end] == nums[end + 1])
                        end--;
                } else if (sum > 0)
                    end--;
                else
                    begin++;
            }
        }
        return ret;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值