3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
public class Solution { private static class ThreeSumEntry { public int begin; public int mid; public int end; private ThreeSumEntry(int begin, int mid, int end) { this.begin = begin; this.mid = mid; this.end = end; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ThreeSumEntry that = (ThreeSumEntry) o; if (begin != that.begin) return false; if (end != that.end) return false; if (mid != that.mid) return false; return true; } @Override public int hashCode() { int result = begin; result = 31 * result + mid; result = 31 * result + end; return result; } } public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (num==null || num.length < 3) { return result; } Arrays.sort(num); //用于结果的去重复 HashMap<ThreeSumEntry,Boolean> map = new HashMap<ThreeSumEntry, Boolean>(); //固定一个数,然后转换成对一个序列求和为指定数字的两个 for (int i=0;i<num.length;i++) { int begin = 0,end = num.length-1; int find2Sum = 0-num[i]; while (begin < end) { //是固定的数 就跳过 if (begin==i) { begin++; continue; } if (end==i) { end--; continue; } if ((num[begin]+num[end])==find2Sum) { ArrayList<Integer> sum = new ArrayList<Integer>(); int[] temp = {num[i],num[begin],num[end]}; Arrays.sort(temp); ThreeSumEntry ts = new ThreeSumEntry(temp[0],temp[1],temp[2]); if (map.containsKey(ts)) { //如果是个重复的结果的数就跳过 begin++; end--; continue; } else { map.put(ts,true); } sum.add(temp[0]); sum.add(temp[1]); sum.add(temp[2]); result.add(sum); //找到一个结果还需要继续查找 begin++; end--; continue; } if ((num[begin]+num[end])>find2Sum) { end--; } if ((num[begin]+num[end])<find2Sum) { begin++; } } } return result; } }