https://leetcode-cn.com/problems/3sum-closest/
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res, i = sum(nums[:3]), 0
while i < len(nums)-2:
left, right = i+1, len(nums)-1
while left<right:
three_sum = nums[i] + nums[left] + nums[right]
if abs(res-target) > abs(three_sum-target):
res = three_sum
if three_sum == target:
return res
elif three_sum > target:
right -= 1
else:
left += 1
i += 1
return res
优化一下,时间反而变长,可能和测试用例有关:
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res, i = sum(nums[:3]), 0
while i < len(nums)-2:
left, right = i+1, len(nums)-1
while left<right:
three_sum = nums[i] + nums[left] + nums[right]
if abs(res-target) > abs(three_sum-target):
res = three_sum
if three_sum == target:
return res
elif three_sum > target:
right -= 1
while left < right and nums[right] == nums[right+1]:
right -= 1
else:
left += 1
while left < right and nums[left] == nums[left-1] :
left += 1
i += 1
while i < len(nums)-2 and nums[i] == nums[i-1]:
i += 1
return res
加个条件会更优:
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res, i = sum(nums[:3]), 0
while i < len(nums)-2:
left, right = i+1, len(nums)-1
cond = nums[i] + nums[i+1] + nums[i+2]
if cond > target:
if abs(cond-target) < abs(res-target):
res = cond
break
while left<right:
three_sum = nums[i] + nums[left] + nums[right]
if abs(res-target) > abs(three_sum-target):
res = three_sum
if three_sum == target:
return res
elif three_sum > target:
right -= 1
else:
left += 1
i += 1
return res