Self-Explanatory Java Solution using two pointers


  • 3
    C
      public int threeSumClosest(int[] nums, int target) {
            if(nums==null || nums.length<3)
                return -1;
            Arrays.sort(nums);
            int result = 0;
            int diff = Integer.MAX_VALUE;
            for(int i=0; i<nums.length-1; i++){
                if(i>0 && nums[i] == nums[i-1])
                    continue;
                int j = i+1;
                int k = nums.length-1;
                while(j<k){
                    int sum = nums[i]+nums[j]+nums[k];
                    if(diff> Math.abs(target-sum)){
                        result=sum;
                        diff = Math.abs(target-sum);
                    }if(sum==target){
                        return sum;
                    }else if(sum<target){
                        j++;
                    }else
                        k--;
                }
                
            }
            return result;
        }

Log in to reply
 

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