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个数字
最新推荐文章于 2024-10-09 11:13:12 发布