15. 3Sum 3个数字的和

题目:3Sum 3个数字的和

难度:中等

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]
]

题意解析:

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

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

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

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

解题思路一:

由于数组中可能会存在大量重复的元素,而给定的数组也都是无序的,所以在查找元素时,我们需要先对数组进行排序操作,防止每次都取进行是否重复的判断,接下来就是以左边第一个元素为起点,然后从第二个和最后一个元素为b和c,来查找是否存在a+b+c=0,如果结果大于0,那么我们需要缩小c也就是左右边元素的位置,否则就增大左边元素b的位置,以此类推。

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if ((i>0) && (nums[i]==nums[i-1]))
            continue;
            int l = i + 1, r = n-1;
            while (l < r){
                if (nums[i] + nums[l] + nums[r] > 0){
                    r--;
                }else if (nums[i] + nums[l] + nums[r] < 0){
                    l++;
                }else{
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    lists.add(list);
                    while(l+1 < n-1 && nums[l] == nums[l + 1]) l++;
                    while(r-1 > 0 && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                }
            }
        }
        return lists;
        
    }

此算法的时间复杂度为O(n²)

提交代码之后:

Runtime: 28 ms, faster than 97.84% of Java online submissions for 3Sum.

Memory Usage: 48.4 MB, less than 70.27% of Java online submissions for 3Sum.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值