问题描述
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).
实现方案
def three_sum_closest(nums, target):
nums.sort()
result = nums[0] + nums[1] + nums[-1]
for i in range(len(nums) - 1):
if i == 0 or (i != 0 and nums[i] != nums[i - 1]):
low = i + 1
high = len(nums) - 1
while low < high:
s = nums[i] + nums[low] + nums[high]
if s == target:
return target
if s < target:
low += 1
else:
high -= 1
if abs(s - target) < abs(result - target):
result = s
return result
print three_sum_closest([0, 2, 1, -3], 1)