题目:
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).
题意: 给出一个数组和一个目标值,在该数组中找到三个数,使之和与目标值最为接近,假设唯一存在最为接近的值。
思路: 此题解法核心思路与上一题(15题)几乎一致,使用三个指针即可,区别是上一题要求找出数组中三个数值和与target相等的所有不重复数组(需要去重),就是要求三个指针对应的数值和与target相等,而这一题要求和与target最为接近,只需返回最为最终三个数的和即可。使用绝对值比较,保留绝对值最小的那三个数的和,时间复杂度为
O
(
n
)
O(n)
O(n)。
代码仅供参考:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
n = len(nums)
Sum = nums[0] + nums[1] + nums[2]
for i in range(n-2):
re_nums = nums[i+1:]
j = 0
k = len(re_nums) - 1
while j < k:
result = nums[i] + re_nums[j] + re_nums[k]
if abs(result-target) < abs(Sum - target):
Sum = result
if result < target:
j += 1
elif result > target:
k -= 1
else:
return result
return Sum