Description
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
给定一个包括 n 个整数的数组 S,找出 S 中的三个整数使得他们的和与给定的数 target 最接近。返回这三个数的和。假定每组输入只存在一个答案。
例如,给定数组 S = {-1 2 1 -4}, 并且 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Solutions
先排序。设个diff
为三数之和sum
与target
的绝对差,从表头开始,对剩下的做两数之和,当diff
比预设的mindiff
小时,替换mindiff
。如果sum>target
则right
左移,反之右移(因为已经排好序)。
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 16 21:03:01 2018
@author: Saul
"""
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
mindiff = 10000
nums.sort()
res = 0
for i in range(len(nums)):
left = i+1
right = len(nums)-1
while left < right:
sum = nums[left] + nums[right] + nums[i]
diff = abs(target - sum)
if diff < mindiff:
mindiff = diff
res = sum
if target == sum:
return sum
elif sum < target:
left += 1
else:
right -= 1
return res