LeetCoder 解题报告 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.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
题意:给定一个数组,找出其中的三个数,使之三个数的和为0,并输出这三个数,按从小到大输出,如果有多组就全部输出。

分析:在 LeetCode 解题报告 Two Sum 这篇文章中介绍了三种方法,此题是这个题的升级版,这个题如果用暴力解决那么将是O(n3)的时间复杂度,如果用HashMap也是不方便,因为数据是可重复的。

接下来就直接看代码

public List<List<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
        List<List<Integer>> list = new ArrayList<List<Integer>> ();
        int first, end, mid;
        //遍历数组
        for(int i = 0; i < num.length-2; i++) {
        	if(i==0 || num[i] > num[i-1]) {
	        	first = i;
	        	end = num.length - 1;
	        	mid = first + 1;
	        	if(num[first] > 0 || num[end] < 0)
	        		break;
	        	while(mid < end) {
	        		int sum = num[first] + num[mid] + num[end];
	        		if(sum == 0) {
	        			ArrayList<Integer> each = new ArrayList<Integer>();
	        			each.add(num[first]);
	        			each.add(num[mid]);
	        			each.add(num[end]);
	        			if(!list.contains(each))
	        				list.add(each);
	        			mid++;
	        			end--;
	        			while(mid < end && num[end] == num[end-1])
	        				end--;
	        			while(mid < end && num[mid] == num[mid+1])
	        				mid ++;
	        		}
	        		else if(sum < 0) {
	        			mid++;
	        		}
	        		else 
	        			end--;
	        	}
        	}
        }
        return list;
    }

思路其实就很简单了,就是锁定第一个值遍历,剩下的两个的数,按照数组中寻找两个数的和是定值来解决就ok了。

如果按着思路写出的代码提交会有出现超时现象,那么我们就要优化了。

这里面做了很多的优化,比如:

if(i==0 || num[i] > num[i-1])
这里是防止相同数据输入

while(mid < end && num[end] == num[end-1])
	        				end--;
	        			while(mid < end && num[mid] == num[mid+1])
	        				mid ++;
这里避免不必要的重复








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值