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.
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).
Show Similar Problems
Have you met this question in a real interview?
Yes
No
O(n*n) time O(1) space
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
difference = 1 << 31
nums_length = len(nums)
for index in range(nums_length - 1):
left = index + 1
right = nums_length - 1
while left < right:
num_sum = nums[index] + nums[left] + nums[right]
current_difference = target - num_sum
if abs(current_difference) < difference:
difference = abs(current_difference)
result = num_sum
if num_sum == target:
return num_sum
elif num_sum <= target:
left += 1
else:
right -= 1
return result