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的三個數(shù)腔彰,返回他們的和
思路
和15號問題差不多整以,把判斷條件改一下即可
代碼
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len =nums.length;
int res=Integer.MAX_VALUE;//存最后的和
int minv=Integer.MAX_VALUE;//存最小的差
for (int i = 0; i < nums.length; i++) {
if (i>0&&nums[i]==nums[i-1]) {
continue;
}
int begin = i+1;
int end=len-1;
while (begin<end) {
int sum=nums[i]+nums[begin]+nums[end];
int minus=sum-target;
if (minus==0) {
return sum;
}else if (minus>0) {
if (minus<minv) {
minv=minus;
res=sum;
}
end--;
}else {
if (-minus<minv) {
minv=-minus;
res=sum;
}
begin++;
}
}
}
return res;
}