3 Sum Closest

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.

Example:

1
2
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).

思路:
思路和3sum类似,还是找一个基准值和两个指针lp和rp不过有些地方简化了,只需要获得一个值。因此,对应的组合不用存取,只需要不断的更新最接近的值即可。

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def threeSumClosest(nums, target):
if not len(nums):
return 0

nums.sort()
res = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
lp = i + 1
rp = len(nums) - 1
while lp < rp:
closest = nums[i] + nums[lp] + nums[rp]
if abs(closest - target) < abs(res - target):
res = closest
if closest < target:
lp += 1
elif closest > target:
rp -= 1
else:
lp += 1
rp -= 1
return res