My java Solution


  • 0
    C
      import java.util.Arrays;
    
       public class Solution3 {
    public int threeSumClosest(int[] nums, int target) {
    	int mid = 0,left,right;
    	int min = Integer.MAX_VALUE;
    	Arrays.sort(nums);
    	for(int i=1;i<nums.length-1;i++)
    	{
    		mid = nums[i];
    		left = i-1;
    		right = i+1;
    		while(left>=0 && right<nums.length)
    		{
    			int sum = mid+nums[right]+nums[left];
    			if(sum == target)
    				return sum;
    			min = Math.abs(min)>Math.abs(target-sum)?target-sum:min;
    			if(sum>target)
    			{
    				left--;
    			}
    			else if(sum<target)
    			{
    				right++;
    			}
    		}			
    	}
    	return target-min;
    }
    

    }


Log in to reply
 

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