3Sum Closest Leetcode


#1

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

#2

The below code sorts the given numbers first and then uses two pointers to find out the closest sum.

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums==null || nums.length==0) return 0;
        Arrays.sort(nums);
        int minDiff = Integer.MAX_VALUE, minSum = Integer.MIN_VALUE;
        int sum = 0 , n = nums.length, j=0, k=0;
        for(int i=0;i<n;i++){
            j=i+1; k=n-1;
            while(j<k){
                sum = nums[i]+nums[j]+nums[k];
                if(minDiff >  Math.abs(target-sum)){
                   minDiff = Math.abs(target-sum) ;
                   minSum = sum;
                }
                if(sum > target){
                    k--;
                } else{
                    j++;
                }
            }
        }
        
        return minSum;
    }
}