15. 3Sum java solutions

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: 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]
]

Subscribe to see which companies asked this question

 1 public class Solution {
 2     List<List<Integer>> ans = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> threeSum(int[] nums) {
 4         if(nums == null || nums.length < 3) return ans;
 5         Arrays.sort(nums);
 6         for(int i = 0; i < nums.length - 2; i++){
 7             if(i > 0 && nums[i] == nums[i-1]) continue;
 8             find3sum(i+1,nums.length-1,nums,0-nums[i]);
 9         }
10         return ans;
11     }
12     
13     public void find3sum(int s,int e,int[] nums,int target){
14         while(s < e){
15             int sum = nums[s] + nums[e];
16             if(sum == target){
17                 List<Integer> tmp = new ArrayList<Integer>();
18                 tmp.add(0-target);
19                 tmp.add(nums[s++]);
20                 tmp.add(nums[e--]);
21                 ans.add(tmp);
22                 while(s < nums.length-1 && nums[s] == nums[s-1])s++;
23                 while(e >= 0 && nums[e] == nums[e+1])e--;
24             }else if(sum < target) s++;
25             else e--;
26         }
27     }
28 }

使用求解2sum 的方式来做,要注意的是重复元素的处理。先排序,然后略过重复元素

posted @ 2016-07-07 17:22  Miller1991  阅读(182)  评论(0编辑  收藏  举报