题目大概
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.
- 1 题目大概是说给一个数组找到三个整数使其相加的和最接近所给的target
- 2 大概的思路就是说固定一个数,然后另外两个数分别从左和右移动
如果两个数相加的和大于目标和固定的那个数的距离,那么进一步比较最左侧的两个数的和,如果还是大于的话,则比较当时的最近的距离和这个,并把最小的距离存储
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
i = 0
size = len(nums)
if size < 3:
return 0
ans = nums[0] + nums[1] + nums[size - 1]
nums.sort()
while i < size - 2:
j = i + 1
k = size - 1
temp = target - nums[i]
while j < k:
if nums[j] + nums[k] == temp:
return target
if nums[j] + nums[k] > temp:
if nums[j] + nums[j + 1] >= temp:
if nums[j] + nums[j + 1] -temp < abs(ans - target):
ans = nums[i] + nums[j] + nums[j + 1]
break
tempans = nums[i] + nums[j] + nums[k]
if (tempans - target) < abs(ans - target):
ans = nums[i] +nums[j] +nums[k]
k -= 1
if nums[j] + nums[k] < temp:
if nums[k] + nums[k - 1] <= temp:
if abs(nums[k] + nums[k - 1] - temp) < abs(ans - target):
ans = nums[i] + nums[k - 1] + nums[k]
break
tempans = nums[i] + nums[j] +nums[k]
if abs(tempans - target) < abs(ans - target):
ans = nums[i] + nums[j] + nums[k]
j += 1
i += 1
if ans == target:
return target
return ans