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最接近
思路类似于3sum
首先排序数组让数组从小到大排列
然后选出一个初始result值
然后sum得和应该为 int sum = nums[start]+nums[end]+nums[i];
for来遍历nums【i】每次往后推一个数
在num【i】确定后确定start 和 end
最后减target值越小就越接近
最接近的值为result;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = nums[0]+nums[1]+nums[nums.length-1];
for(int i= 0;i<nums.length-2;i++){
int start = i+1;
int end = nums.length-1;
while(start<end){
int sum = nums[start]+nums[end]+nums[i];
if(sum>target){
end--;
}
else{
start++;
}
if(Math.abs(sum- target) < Math.abs(res- target)){
res = sum;
}
}
}
return res;
}
}