题目描述:
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).
思路同3Sum完全相同
public class ThreeSum_Closest {
public static int getCloset(int array[],int target)
{
int result=0;
int closest=Integer.MAX_VALUE;
Arrays.sort(array);
for(int i=0;i<array.length-2;i++)
{
if(i>0&&array[i]==array[i-1])
{
continue;
}
int start=i+1;
int end=array.length-1;
while(end>start)
{
if(start>i+1&&array[start]==array[start-1])
{
start++;
continue;
}
if(end<array.length-1&&array[end]==array[end+1])
{
end--;
continue;
}
int sum=array[i]+array[start]+array[end];
int difference=Math.abs(sum-target);
if(difference<closest)
{
closest=difference;
result=sum;
}
if(sum==target)
{
return sum;
}
if(sum>target)
{
end--;
}
if(sum<target)
{
start++;
}
}
}
return result;
}
public static void main(String[] args) {
int num[]={-1,2,1,-4};
int target=1;
System.out.println(getCloset(num,target));
}
}