题目:
给定一个包括 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):
nums.sort()
sum = nums[0] + nums[1] + nums[2] if len(nums) >= 3 else None
for each in range(len(nums) - 2):
if nums[each] == nums[each - 1]:
continue
count1 = each + 1
count2 = len(nums) - 1
while count2 > count1:
temp = nums[count1] + nums[count2] + nums[each]
rest = temp - target
sum = temp if abs(sum - target) > abs(temp - target) else sum
if rest < 0:
count1 += 1
while count2 > count1 and nums[count1] == nums[count1 - 1]:
count1 += 1
elif rest > 0:
count2 -= 1
while count2 > count1 and nums[count2] == nums[count2 + 1]:
count2 -= 1
else:
return target
return sum
s = Solution()
print(s.threeSumClosest([-1,0,1,1,55],3))