title: Find three Numbers with Sum closest to a given number
body: <p>I am trying to solve a problem where, </p>
  
  <blockquote>
    <p>Given an array S of n integers, find three integers in S such that the
    sum is closest to a given number, target. Return the sum of the three
    integers. You may assume that each input would have exactly one
    solution.</p>
  
  <pre><code>For example, given array S = {-1 2 1 -4}, and target = 1.
  
  The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
  </code></pre>
  </blockquote>
  
  <p>My solution is: take a number out (number_1) from the array, set the target to target - that number and find two other numbers which are closest to the new target. This way: number_1 + number_2 + number_3 will be closest as number_2 + number_3 will be closest to target - number_1.</p>
  
  <p>I tried my solution at <a href="https://leetcode.com/problems/3sum-closest/description/" rel="nofollow noreferrer">https://leetcode.com/problems/3sum-closest/description/</a>.</p>
  
  <p>My solution is:</p>
  
  <pre><code>def threeSumClosest(nums, target):
      """
      :type nums: List[int]
      :type target: int
      :rtype: int
      """
      closest_sum = nums[0] + nums[1] + nums[2]
  
      for i in range(len(nums)):
  
          # Create temp array excluding a number
  
          if i!=len(nums)-1:
              temp = nums[:i] + nums[i+1:]
  
          else:
              temp = nums[:len(nums)-1]
  
  
          # Sort the temp array and set new target to target - the excluded number
  
          temp = sorted(temp)            
          l, r = 0, len(temp) -1 
          t = target - nums[i]
  
          while(l&lt;r):
  
              if temp[l] + temp[r] == t:
                  return target
  
              elif temp[l] + temp[r] &gt; t:
  
                  if abs(temp[l] + temp[r] + nums[i] - target) &lt; abs(closest_sum - target):
                      closest_sum = temp[l] + temp[r] + nums[i]
  
                  r = r - 1
  
              else:
  
                  if abs(temp[l] + temp[r] + nums[i] - target) &lt; abs(closest_sum - target):
                      closest_sum = temp[l] + temp[r] + nums[i]
  
                  l = l + 1
  
  
          return closest_sum
  </code></pre>
  
  <p>It passes 80 test cases out of 125, so the solution logic looks fine enough for me.</p>
  
  <p>It fails for:</p>
  
  <pre><code>Input:
  [0,2,1,-3]
  1
  Output:
  3
  Expected:
  0
  </code></pre>
  
  <p>Can't understand why it fails and how to make my logic consistent.</p>
  
  <p>Thanks for your help.</p>