3Sum

【题目】

Given an array S of n integers, are there elements abc 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)

【分析】

1.使用两头逼近的方法,利用两层循环。第一层循环遍历每一个元素,在第二层循环里两头逼近找出满足条件的结果

2.要考虑数据元素重复的问题,若第二层循环中遇到相同元素,需要继续向前;

3.第一层循环中晕倒相同元素,也需要继续向前

public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        Arrays.sort(res);
        for(int i=0;i<num.length;i++) {
            int start=i+1;
            int end=num.length-1;
            int target=0-num[i];
            while(start<end) {
               if(target==num[start]+num[end]) {
                   Lsit<Integer> temp=new ArrayList<Integer>();
                   temp.add(num[i]);
                   temp.add(num[start]);
                   temp.add(num[end]); 
                   res.add(temp);
                   start++;
                   end--;
                   while(start<end&&num[start]==num[start-1])
                       start++;
                   while(start<end&&num[end]==num[end+1])
                       end--;       
               }else if(num[start]+num[end]>target)
                   end--;
               else 
                   start++;
            }
            while(i<num.length-1&&num[i]==num[i++])
               i++;
        }
        return res;
    }
}        

【算法实现】 

 

原文地址:https://www.cnblogs.com/hwu2014/p/4460497.html