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)
思想: 把3sum转换为2Sum,并且查找时避免重复,将重复项去除。
- public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
- if(num == null || num.length < 3) return res;
- int lg = num.length;
- Arrays.sort(num);
- for(int i=0;i<=lg-3;i++) {
- if(i>0 && num[i] == num[i-1]) continue;
- ArrayList<Integer> cur = new ArrayList<Integer>();
- int target = 0-num[i];
- int low = i+1;
- int high = lg-1;
- while(low<high) {
- if(num[low]+num[high]==target) {
- cur.add(num[i]);
- cur.add(num[low]);
- cur.add(num[high]);
- res.add(new ArrayList<Integer>(cur));
- low++;
- while(low<high && num[low]==num[low-1]) low++;
- high--;
- while(high>low && num[high]==num[high+1]) high--;
- cur.clear();
- } else if(num[low]+num[high]>target) {
- high--;
- while(high>low && num[high] == num[high+1]) high--;
- } else {
- low++;
- while(low<high && num[low]==num[low-1]) low++;
- }
- }
- }
- return res;
- }

浙公网安备 33010602011771号