给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解答:
public static List<List<Integer>> threeSum(int[] sums){ /*申明结果*/ List<List<Integer>> res=new ArrayList<>(); /*当数组元素为空或者元素小于3时直接返回结果*/ if(sums==null||sums.length<3){ return new ArrayList<>(); } /*先对数组进行排序*/ Arrays.sort(sums); /*数组长度*/ int length=sums.length; /*申明一个指针从最小位置开始,后面i是k的后续下标,j是从尾部开始遍历*/ for(int k=0;k<length-2;k++){ /*当k下标对应的值>0时,说明总和要大于0终止整个循环*/ if(sums[k]>0){ break; } /*当k的前一个与当前值一样时,终止本次循环*/ if(k>0&&sums[k-1]==sums[k]){ continue; } /*定义i*/ int i=k+1; /*定义j*/ int j=length-1; while(i<j){ int kv=sums[k]; int iv=sums[i]; int jv=sums[j]; int tmp=kv+iv+jv; if(tmp==0){ List<Integer> r=new ArrayList<>(3); r.add(kv); r.add(iv); r.add(jv); res.add(r); /*当和为0时,比对i和i后面的数是否相等,如果相同则i加1*/ while (i<j&&sums[i]==sums[i+1]){ i++; } /*当和为0时,比对j和j后面的数是否相等,如果相同则j减1*/ while (i<j&&sums[j]==sums[j-1]){ j--; } /*同时i加1和j减1*/ i++; j--; }else if(tmp<0){ /*i加1*/ i++; }else{ /*j减1*/ j--; } } } return res; }
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum