15. 3Sum

    /*
     * 15. 3Sum
     * 2016-4-15 by Mingyang
     * 这里我开始犯的错误在于忘了在三个相加等于0的时候应该start++并且end--
     * 另外一个改进就是刚开始用HashSet来做,那样的话就浪费了很多时间
     * 这个地方采用去掉重复的做法更好一点
     */
     public static List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            int len=nums.length;
            Arrays.sort(nums);
            if(nums==null||len<3)
               return res;
               for(int i=0;i<len;i++){
                  if (i == 0 || (i > 0 && nums[i] != nums[i-1])) {
                  //这个if在于去掉第一个数的重复的地方,不能跟前面的一个相等
                   int start=i+1;
                   int end=len-1;
                   while(start<end){
                       List<Integer> temp=new ArrayList<Integer>();
                       if(nums[start]+nums[end]<-nums[i]){
                           start++;
                       }else if(nums[start]+nums[end]>-nums[i]){
                           end--;
                       }else{
                           temp.add(nums[i]);
                           temp.add(nums[start]);
                           temp.add(nums[end]);
                           res.add(temp);
                           while (start < end && nums[start] == nums[start+1]) start++;
                           //这里在于去掉第二个数重复的地方,只要跟后面的相等就跳过
                           while (start < end && nums[end] == nums[end-1]) end--;
                           //这里就是第三个重复的地方,只要跟前面的相等就跳过
                           start++;
                           end--;
                       }
                   }
                  }
               }               
               return res;
        }
原文地址:https://www.cnblogs.com/zmyvszk/p/5397442.html