原题链接:https://leetcode.com/problems/3sum-closest/
思路:与15题类似,i从左往右遍历,j、k分别从左、右开始遍历。但不同之处在于,当遇到nums[j]+nums[k] ? target - nums[i],中间的符号改变时,便可以直接将前后两次的sum与target比较,然后输出更接近的那个了。
代码:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
result = float('inf')
i = 0
while i < len(nums)-2:
target1 = target - nums[i]
j = i+1
k = len(nums)-1
while j < k:
if abs(result-target) > abs(nums[i]+nums[j]+nums[k]-target):
result = nums[i]+nums[j]+nums[k]
if nums[j]+nums[k] < target1:
j += 1
elif nums[j]+nums[k] > target1:
k -= 1
elif nums[j]+nums[k] == target1:
return target
i += 1
while i < len(nums)-2:
if nums[i]!=nums[i-1]:
break
i += 1
return result
参考代码:https://www.cnblogs.com/chruny/p/4820473.html
网友评论