Most concise Java Solution

  • 1

    The code is self-explaining.

    1. Sort the array.
    2. For every element at position i ( from 0 to n-3), use two pointer to find all possible closest combination.
    3. Add some check condition to skip duplicates.
    public int threeSumClosest(int[] nums, int target) {
            int closest = nums[0]+nums[1]+nums[2];
            int n=nums.length;
            for(int i=0; i<n-2; ++i){
                // skip i because when we process i-1 we have checked all these sums
                if(i>0 && nums[i]==nums[i-1]) continue;
                int low=i+1, high=n-1;
                    int sum = nums[low]+nums[high]+nums[i];
                    if(sum == target) return target;
                    else if(sum > target){
                        if(sum-target < Math.abs(closest-target)){
                            closest = sum;
                        // skip the same number
                        while(--high>low && nums[high]==nums[high+1]);
                        if(target-sum < Math.abs(closest-target)){
                            closest = sum;
                        // skip the same number
                        while(++low<high && nums[low]==nums[low-1]);
            return closest;

Log in to reply

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