LeetCode-15 3Sum(求3数和为零的情况总数)

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)

 

思路:等同于求两个数和的相反数是否存在于这个数组中。可以延伸到K sum的问题。

public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
    	List<List<Integer>> list = new ArrayList<>();
    	Arrays.sort(num);
    	int start = 0;
    	while (start < num.length-2) {
    		if (start == 0 || num[start] != num[start-1] ) {
    			//留意判断条件,之前写的是start与start+1不等,导致一直不对。。
	    		int instart = start+1;
	    		int inlast = num.length-1;
	    		while (instart < inlast) {
					if (num[instart] + num[inlast] == -num[start]) {//这里可以考虑用二分法查找来优化。
						List<Integer> temp = new ArrayList<Integer>();
						temp.add(num[start]);
						temp.add(num[instart]);
						temp.add(num[inlast]);
						list.add(temp);
						do {
							inlast--;//重复的数在这里直接跳过。
						} while (num[inlast] == num[inlast+1] && instart < inlast);
						do{
							instart++;
						} while(num[instart] == num[instart-1] && instart < inlast);
					}else if (num[instart] + num[inlast] > -num[start]) {
						inlast--;
					}else {
						instart++;
					}
				}
    		}
    		start++;
		}
    	return list;
    }
}

Runtime: 358 ms

更多收获可参考(个人觉得很棒):Summary for LeetCode 2Sum, 3Sum, 4Sum, K Sum

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值