题目: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).
思路:该题的题意是让我们在一个数组中找出三个数,是它们的和最靠近给定的target值,我们可以将该题简化为在给定第一个数的情况下找出两个数使它们的和最靠近给定的target值,对第一个数逐个遍历便可以找到所有的值,而如果想要找出这两个数,暴力解法是在所有数中找出它们的所有组合,复杂度为O(n^2),整个算法的复杂度为O(n^3),会超时。原因是我们在寻找这两个数的时候进行了一些不必要的比较,比如在[1,2,3]中我们需要寻找最靠近3的两个数的和,一开始我们找到(1,3)的组合这时我们再寻找(2,3)的组合就没有必要了,因为此时已经更加偏移了目的。我的思路是将这些数进行排序,然后设置两个指针,分别指向排序后的数组的头部和尾部,如果此时这两个数的和比target小,我们就可以将头部指针前移,此时找到的两个数之和必定比原来的大,再将新的组合和原先的组合进行比较,比较哪一个更加接近target便取哪个,在两个指针重叠使便退出循环,此时复杂度为O(n),整个算法的复杂度为O(n^2)
答案:
class Solution:
def threeSumClosest(self, nums, target):
numbers=sorted(nums)
k=0;
sum=numbers[0]+numbers[1]+numbers[2]
while k<len(nums)-2:
i=k+1
j=len(nums)-1
while i!=j:
su=numbers[k]+numbers[i]+numbers[j]
if(abs(target-su)<abs(target-sum)):
sum=su
if(target-su)==0:
return su
elif target-su>0:
i=i+1
else:
j=j-1
k=k+1
return sum