求一个数组中三个数和为0的组合

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

实现:

这个想法是对输入数组进行排序,然后遍历三元组的可能第一个元素的所有索引。 对于每个可能的第一个元素,我们进行阵列剩余部分的标准双向2Sum扫描。 同样,我们想跳过相等的元素,以避免在答案中重复,而不会像这样设置或混淆

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class threeSum {
	public static List<List<Integer>> threeSum(int[] num){
		Arrays.sort(num);
		List<List<Integer>> list = new LinkedList<>();
		
		for(int i=0; i<num.length; i++){
			if(i==0 || (i>0 && num[i] != num[i-1])){
				int sum = 0 - num[i];
				int l = i + 1;
				int h = num.length-1;
				
				while(l < h){
					if(num[l]+num[h] == sum){
						list.add(Arrays.asList(num[i],num[l],num[h]));
						while((l < h) && (num[l]==num[l+1])) l++;
						while((l < h) && (num[l]==num[h-1])) h--;
						l++;
						h--;
					}else if(num[l] + num[h] < sum){
						l++;
					}else{
						h--;
					}
				}
			}
		}
		return list;
	}
	
	
	
	public static void main(String[] args) {
		int[] num = {-1,0,1,2,-1,-4};
		List<List<Integer>> list = threeSum(num);
		System.out.println(list.toString());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值