Given an array S of n integers, are there elements a, b, c 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());
}
}