【题目】
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.
【举例】
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
【题目翻译】
给定一个数组和一个target, 在该数组里找和最接近target的三元组, 返回它的和。
【解题思路】
一开始我想着用回溯法解决这个问题, 遍历所有可能的三元组, 在这个过程中记录最接近的和。
写完代码以后发现运行超时。
然后我们发现可以用解决三和问题的通用解法:
首先假设最接近的和是result=nums[0] + nums[1] + nums[len(nums)-1](ps:初始值一般尽可能设为最开始判断的三元组)
然后遍历所有可能的起点i, 用双指针指向剩余元素里面的第一个元素i+1, 和最后一个元素len(nums)-1
判断当前三元组的和sum_是否更接近target, 如果是, 更新一下result
然后判断如果sum_ < target, lo += 1
否则hi -= 1
在遍历起点的时候, 如果该起点nums[i] == nums[i-1], 那么该起点的情况就不用再考虑, 因为, 该起点能找到的最接近的和, 已经包括在上一个起点之中。
【代码实现】
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = nums[0] + nums[1] + nums[len(nums)-1]
for i in range(len(nums)-2):
if i == 0 or nums[i] != nums[i-1]: #如果当前起点元素等于前面一个元素, 不用判断
lo = i + 1
hi = len(nums) - 1
while lo < hi:
sum_ = nums[i] + nums[lo] + nums[hi]
#当前和更接近target, 更新result的值
result = sum_ if abs(sum_ - target) < abs(result - target) else result
if sum_ < target:
lo += 1
else:
hi -= 1
return result