Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
和3 sum问题类似
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
print(nums)
c = abs(nums[0] + nums[1] + nums[2] - target)
ans=nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
start = i + 1
end = len(nums) - 1
while start < end:
tmp=nums[start] + nums[end] + nums[i]
if abs(tmp - target) < c:
c = abs(tmp - target)
ans=tmp
if tmp<target:
start+=1
elif tmp>target:
end=end-1
else:
return target
return ans