题目

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

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def threeSumClosest(self, nums, target):
nums.sort()
z = 1000
r = []
for i in range(0, len(nums)):
a, b = 0, len(nums)-1
while True:
a = a if a != i else a + 1
b = b if b != i else b - 1
if a >= b:
break
c = nums[a] + nums[b] + nums[i]
if c == target:
return nums[i] + nums[a] + nums[b]
elif c > target:
if c-target < z:
z = c-target
r = [nums[i], nums[a], nums[b]]
b -= 1
else:
if target-c < z:
z = target-c
r = [nums[i], nums[a], nums[b]]
a += 1
return r[0] + r[1] + r[2]