Java solution based on twoSum implementation with 8ms.


  • 0
    public class Solution {
    List<List<Integer>> res =new ArrayList<List<Integer>>();
    public List<List<Integer>> threeSum(int[] nums) {
       Arrays.sort(nums);  
       for(int i=0;i<nums.length-2;i++){
           if(i>0&&nums[i]==nums[i-1])   continue;   // to exclude the duplicated number
           twoSum(0-nums[i],nums,i+1,nums.length-1);
       }
       return res;
    }
    private void twoSum(int target,int[] nums, int start,int end){ 
        int i=start,j=end;
        while(i<j){
            List<Integer> subres=new ArrayList<Integer>();
            int sum=nums[i]+nums[j];
            if(sum==target){
                subres.add(0-target);
                subres.add(nums[i]);
                subres.add(nums[j]);
                res.add(subres);
               do {
                    i++;
                }while(i < end && nums[i] == nums[i-1]);   // to exclude the duplicated number
                do {
                    j--;
                } while(j >= 0 && nums[j] == nums[j+1]); // to exclude the duplicated number
            }
            else if(sum<target) i++;
            else j--;
        }
    }
    

    }


Log in to reply
 

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