一、leetcode地址
https://leetcode.com/problems/3sum-closest/
二、问题描述
三、代码实现
语言:Python3
代码:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
print(nums)
n = len(nums)
gap = float('inf')
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
l,r = i+1,n-1
while l<r:
temp = nums[i] + nums[l] + nums[r]-target
if temp > 0:
r -= 1
elif temp < 0:
l += 1
else:
return target
if abs(temp) < abs(gap):gap = temp
return target+gap