题目
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.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路
排序,两端夹挤,单独变量记录当前最小差异mindif和对应的sum。最后返回的sum就是最小差异对应的sum. 改进:跳过相等的相邻数,对求和无助。
类似题目:15
Javapublic int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int mindif = Integer.MAX_VALUE, closeSum=0, L = num.length;
for(int i=0; i<L-2;){
int j=i+1, k=L-1;
while(j<k){
int S = num[i]+num[j]+num[k];
if(Math.abs(S-target) < mindif){
mindif = Math.abs(S-target); closeSum = S;
}
if(S<target) {j++; while(j<L-1 && num[j]==num[j-1]) j++;}
else {k--; while(k>1 && num[k]==num[k+1]) k--;}
}
i++;
while(i<L-2 && num[i]==num[i-1]) i++;
}
return closeSum;
}
Python
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
mindif,minsum,L = sys.maxint,0,len(nums)
sn = sorted(nums)
for i in range(L-2):
j,k=i+1,L-1
while j<k:
if abs(sn[i]+sn[j]+sn[k]-target) < mindif:
mindif=abs(sn[i]+sn[j]+sn[k]-target)
if mindif==0: return target
minsum=sn[i]+sn[j]+sn[k]
if sn[i]+sn[j]+sn[k] > target: k-=1
else: j+=1
return minsum