题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { if (num.length < 3) {//长度小于3时返回空数组集 ArrayList<ArrayList<Integer>> o = new ArrayList<>(); return o; } else { ArrayList<ArrayList<Integer>> out = new ArrayList<>(); for (int i = 0; i < num.length; i++) {//第一层循环,循环整个数组 int numi = num[i]; int two = 0 - numi; ArrayList<Integer> al = new ArrayList<>(); for (int k = 0; k < num.length; k++) { if (k != i) { al.add(num[k]); } } for (int j = 0; j < al.size(); j++) {//第二层循环,循环除numi之外的其他数 int numj = al.get(j); int one = two - numj; ArrayList<Integer> al0 = new ArrayList<>(); for (int l = 0; l < al.size(); l++) { if (l != j) { al0.add(al.get(l)); } } for (int c = 0; c < al0.size(); c++) {//第三层循环,循环二层的数组中除numj之外的其他数 ArrayList<Integer> out0 = new ArrayList<>(); int numc = al0.get(c); if (numc == one) { out0.add(numi); out0.add(numc); out0.add(numj); out0.sort(Comparator.comparingInt(cc -> cc));//对三元组内部排序 if (!out.contains(out0)) {//将三元组排除重复的之后加入外层返回的数组 out.add(out0); } } } } } //对外层返回的数组排序,若三元组中第一个数字相等,则按第二个数字排序。。 out.sort((cc, ff)-> { int no = 0; if (cc.get(0) > ff.get(0)) { no = 1; } else if (cc.get(0) == ff.get(0) && cc.get(1) > ff.get(1)) { no = 1; } else if (cc.get(0) == ff.get(0) && cc.get(1) == ff.get(1) && cc.get(2) > ff.get(2)) { no = 1; } else { no = -1; } return no; }); return out; } } }