版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28306361/article/details/87718339
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).
代码
class Solution:
def threeSumClosest(self, nums: 'List[int]', target: 'int') -> 'int':
new_nums = sorted(nums)
res = float("inf")
for i in range(0, len(new_nums)-2):
if i >= 1 and new_nums[i] == new_nums[i-1]:
continue
j = i + 1
k = len(nums) - 1
while j < k:
if j >= i + 2 and new_nums[j] == new_nums[j - 1]:
j += 1
continue
if k <len(nums) - 1 and new_nums[k] == new_nums[k + 1]:
k -= 1
continue
if new_nums[j] + new_nums[k] + new_nums[i] == target:
return target
elif new_nums[j] + new_nums[k] + new_nums[i] < target:
if abs(target - new_nums[j] - new_nums[k] - new_nums[i])< abs(target - res):
res = new_nums[j] + new_nums[k] + new_nums[i]
j += 1
elif new_nums[j] + new_nums[k] + new_nums[i] > target:
if abs(target - new_nums[j] - new_nums[k] - new_nums[i])< abs(target - res):
res = new_nums[j] + new_nums[k] + new_nums[i]
k -= 1
return res
其实这个代码就和3Sum那道题差不多了,稍微改动一下,衡量一下到target的距离就可以了。