方法一:暴力破解的方式
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> result=new HashSet<>();
if(nums.length==0||nums==null){
return new ArrayList<List<Integer>>();
}
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
for(int j=i+1;j<nums.length-1;j++){
for(int k=j+1;k<nums.length;k++){
if(nums[i]+nums[j]+nums[k]==0){
List<Integer> temp=new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
}
}
}
}
return new ArrayList<List<Integer>>(result);
}
}
方法二: 排序+双指针(去重)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> arr=new ArrayList<>();
if(nums==null||nums.length<3){
return arr;
}
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
int start=i+1;
int end=nums.length-1;
if(nums[i]>0){
break;
}
//对于重复的条件进行判断
if(i>0&&nums[i]==nums[i-1]){ //对i进行去重
continue;
}
while(start<end){
if(nums[i]+nums[start]+nums[end]==0){
List<Integer> temp=new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[start]);
temp.add(nums[end]);
arr.add(temp);
while(start<end&&nums[end]==nums[end-1]){ //对右侧进行去重
end--;
}
while(start<end&&nums[start]==nums[start+1]){ //对左侧进行去重
start++;
}
start++;
end--;
}else if(nums[i]+nums[start]+nums[end]>0){
end--;
}else{
start++;
}
}
}
return arr;
}
}