My 312ms java solution


  • 1
    D
      public int threeSumClosest(int[] nums, int target) {
                 Arrays.sort(nums);
                int min = Integer.MAX_VALUE;
                int result = target;
                for(int i=0;i<nums.length-2;i++)
                {
                    int start = i+1;
                    int end = nums.length-1;
                    while(start < end)
                    {   
                        int temp_sum = nums[i]+nums[start]+nums[end];
                        
                        if(target < temp_sum)
                        {
                            if(temp_sum-target < min)
                            	{
                            		min = temp_sum-target;
                            		result = temp_sum;
                            	}
                            while(start < end && nums[end]==nums[end-1]) end--;
                            end--;
                        }
                        else
                        if(target > temp_sum)
                        {
                        	 if(target-temp_sum < min)
                         	{
                         		min = target-temp_sum;
                         		result = temp_sum;
                         	}
                         	while(start < end && nums[start]==nums[start+1]) start++;
                            start++;
                        }
                        else return target;
                    }
                }
                return result;
            }

Log in to reply
 

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