forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
27 lines (26 loc) · 904 Bytes
/
Solution.py
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
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
def twoSumClosest(nums, start, end, target):
res = 0
diff = 10000
while start < end:
val = nums[start] + nums[end]
if val == target:
return val
if abs(val - target) < diff:
res = val
diff = abs(val - target)
if val < target:
start += 1
else:
end -= 1
return res
nums.sort()
res, n = 0, len(nums)
diff = 10000
for i in range(n - 2):
t = twoSumClosest(nums, i + 1, n - 1, target - nums[i])
if abs(nums[i] + t - target) < diff:
res = nums[i] + t
diff = abs(nums[i] + t - target)
return res