package 剑指Offer.第二章数组.数组中和为0的三个数字;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* @program:多线程和IO
* @descripton:所有和为0的3个数字的三元组?
* @返回值中不得包含重复的三元组。
* @author:ZhengCheng
* @create:2021/9/26-16:07
**/
public class ThreeNumsAddEqualsZero {
public List<List<Integer>> threenums(int[] num){
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(num);
int i = 0;
while (i < num.length-2) {
twonum(result,i,num);
//注意剔除重复数字
int tempNum = num[i];
while (tempNum == num[i]&& i < num.length -2 ){
i++;
}
}
return result;
}
private void twonum(List<List<Integer>> res, int i, int[] num) {
int j = 0;
int k = num.length -1 ;
while (j < k){
if (num[i] + num[j] + num[k] == 0){
res.add(Arrays.asList(num[i],num[j],num[k]));
//剔除重复的
int tempNum = num[j];
while (num[j] == tempNum && j <k){
j++;
}
}else if (num[i] + num[j] + num[k] > 0){
k--;
}else {
j++;
}
}
}
}
剑指offer-数组中和为0的3个数字
最新推荐文章于 2025-12-13 12:19:21 发布
该博客介绍了如何在已排序的整数数组中找到所有和为0且不重复的三元组。算法通过双指针法避免了重复元素,并确保结果中不含重复的三元组。主要涉及数组操作、排序和二重循环搜索等概念。
1190

被折叠的 条评论
为什么被折叠?



