LeetCode15 - 3Sum

【题目】

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

【思路】

题目含义很简单,从一个数组中找出所有三个数的和为0的组合,在一个组合中,一个数不能重复用,组合不能重复

我的思路很简单,先将数组排序,然后两个两个为一组,在之后的数组中,二分查找找出满足和为0的数,时间复杂度为O(n*n*logn),结果果然排在了比较靠后的位置。

【Java代码】

public class Solution_15_3Sum {	
	public List<List<Integer>> threeSum(int[] nums){
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		Arrays.sort(nums);
		for(int i = 0 ; i < nums.length-2 ; i++){
			if(i > 0 && nums[i] == nums[i-1])
				continue;
			for(int j = i+1; j < nums.length-1 ; j++){
				if(j > i+1 && nums[j] == nums[j - 1])
					continue;
				if(Arrays.binarySearch(nums,j+1,nums.length,0-nums[i]-nums[j])>=0)
					result.add(Arrays.asList(nums[i],nums[j],0-nums[i]-nums[j]));
			}
		}
		return result;
	}
}
【大佬】

所以必须膜拜了大佬们的思路,复杂度为O(n)。

先对数组排序, 从头到尾逐个遍历数组中的元素,对于每一个元素,计算后边剩下的部分能不能找出两个数的和,满足与该元素相加为0。

在寻找两数之和时,分别从首尾向中间遍历,若两数相加小了,则左侧右移,反之则右侧左移。

public List<List<Integer>> threeSum(int[] num) {
    Arrays.sort(num);
    List<List<Integer>> res = new LinkedList<>(); 
    for (int i = 0; i < num.length-2; i++) {
        if (i == 0 || (i > 0 && num[i] != num[i-1])) {
            int lo = i+1, hi = num.length-1, sum = 0 - num[i];
            while (lo < hi) {
                if (num[lo] + num[hi] == sum) {
                    res.add(Arrays.asList(num[i], num[lo], num[hi]));
                    while (lo < hi && num[lo] == num[lo+1]) lo++;
                    while (lo < hi && num[hi] == num[hi-1]) hi--;
                    lo++; hi--;
                } else if (num[lo] + num[hi] < sum) lo++;
                else hi--;
           }
        }
    }
    return res;
}

【提高】

以上代码运行之后可以排在中间位置,而最好的代码与其思路基本相同,唯一区别,是在选定第一个元素时,判断其是否>0,若大于0,则直接返回当前结果。。。。6666,大佬所以为大佬

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值