import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length==0){
return result;
}
//排序
Arrays.sort(num);
//缓存至map中
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<num.length;i++){
map.put(num[i],i);
}
int temp =0;
for(int i=0;i<num.length;i++){
for(int j=i+1;j<num.length;j++){
//遍历任意两数之和,即矩阵上半部分
temp=num[i]+num[j];
//需要的数字,从map中尝试获取
int needNum = 0-temp;
if(map.get(needNum)!=null){
int needIndex =map.get(needNum);
//取到的数据角标非当前两数的角标
if(needIndex!=i&&needIndex!=j){
ArrayList<Integer> resultList = new ArrayList<Integer>();
resultList.add(num[i]);
resultList.add(num[j]);
resultList.add(needNum);
resultList.sort((x,y)->x-y);
//升序排序,去重加入结果队列
if(!result.contains(resultList)){
result.add(resultList);
}
}
}
}
}
return result;
}
}