3Sum

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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)

Analysis

  • Very similar to 3SumCloset, keep 3 pointers
  • Pay attention to avoid repeat values

    Code

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums == null || nums.length==0) {return result;}

        Arrays.sort(nums);

        for(int i=0; i<nums.length-2;i++){
            //make sure 1st pointer is not repeating
            if(i>0 && nums[i]==nums[i-1]) {continue;}
            int str =i+1;
            int end =nums.length-1;
            while(str<end){
                int sum = nums[i]+nums[str]+nums[end];
                if (sum==0) {
                    List<Integer> list = new ArrayList<Integer>(Arrays.asList(nums[i], nums[start], nums[end]));
                    result.add(list); 
                    str++;
                    end--;
                    //make sure 2nd and 3rd pointers are not repeating
                    while(str<end && str<nums.length && nums[str]==nums[str-1]){str++;}
                    while(str<end && end>0 && nums[end]==nums[end+1]){end--;}
                }
                else if(sum < 0) {str++;}
                else {end--;}
            }
        }

        return result;
    }
}