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).
解题思路:使用sum存三数之和,diff保存sum与target之间的差值。
先对数组进行排序,依次遍历数组data中下标i 从0~len-3的数,然后在剩下的i+1~len-1个数中使用二分查找。
找出两个数与data[i]的和与target比较,如果差值小于diff,则将diff和sum都更新改变。
public class Solution {public void quickSort(int [] num, int start, int end){
int left=start;
int right=end;
int data=num[left];
while(left<right){
while(left<right&&num[right]>=data){
right--;
}
if(left<right){
num[left]=num[right];
left++;
}
while(left<right&&num[left]<=data){
left++;
}
if(left<right){
num[right]=num[left];
}
}
num[left]=data;
if(start<left-1){
quickSort(num,start,left-1);
}
if(left+1<end){
quickSort(num,left+1,end);
}
}
public int threeSumClosest(int[] num, int target) {
int rs=num[0]+num[1]+num[2];
int diff=Math.abs(rs-target);
int len=num.length;
if(len==3){
return rs;
}
quickSort(num,0,len-1);
for(int i=0;i<len-2;i++){
int data=num[i];
int left=i+1;
int right=len-1;
while(left<right){
int sum=data+num[left]+num[right];
int distance=Math.abs(sum-target);
if(distance==0){
return sum;
}else if(distance<diff){
diff=distance;
rs=sum;
}
if(sum>target){
right--;
}else if(sum<target){
left++;
}
}
}
return rs;
}
}