# leetcode15 3Sum 从数组中找到三个整数，它们的和为0

## 题目要求

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

## 思路一：无hashset or hashmap

``````    public List<List<Integer>> threeSum2(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int length = nums.length;
if(length<3){
return result;
}
Arrays.sort(nums);

int i = 0;
while(i<length-2){
if(nums[i]>0) break;
int j = i+1;
int k = nums.length - 1;
while(j<k){
int sums = nums[i] + nums[j] + nums[k];
if (sums==0){
}
if (sums<=0){
//消去左侧重复的数字
while(nums[j]==nums[++j] && j < k);
}
if (sums>=0){
//消去右侧重复的数字
while(nums[k--] == nums[k] && j < k);
}

//消去和当前左指针相同的数字
while(nums[i] == nums[++i] && i < nums.length - 2);
}

}
return result;
}``````

## 思路二：有hashmap/hashset

``````public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> list = new ArrayList<List<Integer>>();
HashSet<List<Integer>> set = new HashSet<List<Integer>>();
for(int i=0;i<num.length;i++)
{
for(int j=i+1,k=num.length-1;j<k;)
{
if(num[i]+num[j]+num[k]==0)
{
List<Integer> l= new ArrayList<Integer>();
j++;
k--;
}
else if(num[i]+num[j]+num[k]<0)
j++;
else
k--;
}
}
return list;
}``````