- 外加一层循环,遍历数组所有数,作为第一个数,其他两个与2sum类似,a+b=target结束循环,如果小就a+,如果大就b-
- 将满足条件的结果(三个数字)放入midresult中,midresult是个链表,将midresult放入hashmap中去重
- 再将hashmap中取出来放入result中即可
public class _3Sum {
public static ArrayList threeSum(int[] num) {
Arrays.sort(num);
ArrayList result = new ArrayList();
Map hm = new HashMap();
for (int firstPos = 0; firstPos < num.length; firstPos++) {
int secPos = firstPos + 1;
int thirdPos = num.length - 1;
while (secPos < thirdPos) {
if (num[firstPos] + num[secPos] + num[thirdPos] == 0) {
ArrayList<Integer> midResult = new ArrayList<Integer>();
midResult.add(num[firstPos]);
midResult.add(num[secPos]);
midResult.add(num[thirdPos]);
hm.put(midResult, false);
secPos += 1;
thirdPos -= 1;
} else if (num[firstPos] + num[secPos] + num[thirdPos] < 0) {
secPos += 1;
} else {
thirdPos -= 1;
}
}
}
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
// Entry entry =(Entry) it.next();
// result.add(entry.getKey());
result.add(it.next());
}
return result;
}
public static void main(String[] args) {
// int[] num = { -1, 0, 1, 2, -1, -4,-1,0,1};
int[] num = {0,0,0};
System.out.println(threeSum(num));
}
}