import java.util.*; public class Solution { /* 输入: [-10,0,10,20,-10,-40] 返回值: [[-10,-10,20],[-10,0,10]] */ class Three { int one ; int two ; int three ; Three(int a , int b , int c) { int[] tmp = {a,b,c} ; Arrays.sort(tmp) ; one = tmp[0] ; two = tmp[1] ; three = tmp[2] ; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Three)) return false; Three a = (Three) o; return one == a.one && two == a.two && three == a.three; } @Override public int hashCode() { return Objects.hash(one, two, three); } } public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<>() ; HashSet<Three> set = new HashSet<>() ; Arrays.sort(num) ; for(int i = 0 ; i < num.length ; i ++) { int shen = 0 - num[i] ; int s = 0 ; int e = num.length - 1 ; while(s < e) { if(s == i) { s ++ ; } else if(e == i) { e -- ; } else { int cur = num[s] + num[e] ; if(cur == shen) { Three th = new Three(num[i] , num[s] , num[e]) ; set.add(th) ; int s_old = num[s] ; while(s < e && num[s] == s_old) { s ++ ; } int e_old = num[e] ; while(s < e && num[e] == e_old) { e -- ; } } else if(cur < shen) { s ++ ; } else { e -- ; } } } } //处理set for(Three t : set) { ArrayList<Integer> ele = new ArrayList<>() ; ele.add(t.one) ; ele.add(t.two) ; ele.add(t.three) ; res.add(ele) ; } return res ; } }