3 Sum

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

Pay attention:

  1. Don’t forget to move on "l++" and "r--" after adding a feasible triplet.

  2. Don’t forget to skip duplication, for all i, l and r.

Solution:

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0; i<nums.length-2; i++){
            /* don't forget to skip duplication */
            /* both condiction codes work */
            /* (1) while(i>0 && i<nums.length-2 && nums[i]==nums[i-1]) i++; */
            /* (2) if(i!=0 && nums[i]==nums[i-1]) continue; */
            if(i!=0 && nums[i]==nums[i-1]) continue;
            int two = 0 - nums[i];
            int l=i+1, r=nums.length-1;
            while(l<r){
                if(nums[l]+nums[r]<two){
                    l++;
                } else if(nums[l]+nums[r]>two){
                    r--;
                } else {
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[l]);
                    tmp.add(nums[r]);
                    ans.add(tmp);
                    /* don't forget to move on */
                    l++;
                    r--;
                    /* don't forget to skip duplication */
                    while(l<r && nums[l]==nums[l-1]) l++;
                    while(l<r && nums[r]==nums[r+1]) r--;
                }
            }
        }
        return ans;
    }
}
comments powered by Disqus