Most concise Java Solution


  • 2

    The idea is to choose every number as the a. Then find all the b and c so that a+b+c=0.
    What we need to do next:

    1. skip the same a
    2. set b as the one next to a and c as the last number
    3. if(a+b+c==0) we got one!
      if(a+b+c>0) we need to find a smaller c
      if(a+b+c<0) we need to find a bigger b

    public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new LinkedList<>();
            Arrays.sort(nums);
            for(int i=0;i<nums.length-2;++i){
                if(i>0 && nums[i]==nums[i-1]) continue;
                int l=i+1, r=nums.length-1;
                while(l<r){
                    if(nums[i]+nums[l]+nums[r]==0){
                        res.add(Arrays.asList(nums[i], nums[l], nums[r]));
                        while(++l<r && nums[l]==nums[l-1]); // skip the same b
                        while(--r>l && nums[r]==nums[r+1]); // skip the same c
                    }else if(nums[i]+nums[l]+nums[r]>0){
                        while(--r>l && nums[r]==nums[r+1]);
                    }else{
                        while(++l<r && nums[l]==nums[l-1]);
                    }
                }
            }
            
            return res;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.