Given an array nums of n integers, are there elements a, b, c in nums
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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
所有情况应该是o(n^3)的情况,可以通过HashMap优化到o(n^2)

public List<List<Integer>> threeSum(int[] nums) {
    HashMap<Integer,Integer> map=new HashMap();
    HashSet<List<Integer>> set=new HashSet();
    for(int i:nums){
        if(map.containsKey(i)) map.put(i,map.get(i)+1);
        else map.put(i+1);
    }
    for(int i=0;i<nums.length-1;i++){
        for(int j=i+1;j<nums.length){
            int need=-nums[i]-nums[j];
            if(need==nums[i] == need==nums[i]){
                if(map.get(need)<3) continue;
            }else if(need==nums[i] || need==nums[i]){
                if(map.get(need)<2) continue;
            }else{
                if(map.get(need)<1) continue;
            }
            List<Integer> list=Arrays.asList(new int[]{nums[i],nums[j],need});
        }
    }
    return new ArrayList(set);
}

上面的情况是有问题的,会超时比如都是0的情况,就很有很多无用的判断,还有就是没有解决重复性的问题,解决重复性之前的思路是通过set解决,但为了结局超时的情况,决定排序,也能解决重复性的问题。

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> ret=new ArrayList();
    Arrays.sort(nums);
    Map<Integer,Integer> map=new HashMap();
    for(int i=0;i<nums.length;i++) map.put(nums[i],i);
    for(int i=0;i<nums.length-2;i++){
        if(i>0 && nums[i]==nums[i-1]) continue;
        for(int j=i+1;j<nums.length-1;j++){
            if(j>i+1 && nums[j]==nums[j-1]) continue;
            int need=-nums[i]-nums[j];
            if(need>=nums[j] && map.getOrDefault(need,-1)>j) ret.add(Arrays.asList(nums[i],nums[j],need));
        }
    }
    return ret;
}

再确定一个数后,在后面的有序数组中,也可以通过双指针确定是否存在符合条件的值
public List<List<Integer>> threeSum(int[] nums) {

List<List<Integer>> ret=new ArrayList();
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
    if(i>0 && nums[i]==nums[i-1]) continue;
    int left=i+1;
    int right=nums.length-1;
    while(right>left){
        if(left>i+1 && nums[left]==nums[left-1]) {
            left++;
            continue;
        }
        if(right<nums.length-1 && nums[right]==nums[right+1]){
            right--;
            continue;
        }
        if(nums[i]+nums[left]+nums[right]<0) left++;
        else{
            if(nums[i]+nums[left]+nums[right]==0) ret.add(Arrays.asList(nums[i],nums[left],nums[right]));
            right--;
        }
    }
}
return ret;

}


程浩
21 声望2 粉丝