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).
题意:找到最接近target的三个数的和
代码:此题和之前的3sum在逻辑上没有区别,唯一不同的就是多了一个closest差值,找到这个差值最小的组合即可
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums.length == 3){
return nums[0]+nums[1]+nums[2];
}
int res = 0;
int close = Integer.MAX_VALUE;
Arrays.sort(nums);
for(int i = 0;i<nums.length-2;i++){
if(i==0||nums[i]>nums[i-1]){
int start = i+1;
int end = nums.length-1;
while(start<end){
if(Math.abs(target-nums[i]-nums[start]-nums[end])<=close){
close = Math.abs(target-nums[i]-nums[start]-nums[end]);
res = nums[i] + nums[start] + nums[end];
}
if(target-nums[i]-nums[start]-nums[end]>0){
start++;
}else if(target-nums[i]-nums[start]-nums[end]<0){
end--;
}else{
return res;
}
}
}
}
return res;
}
}