最接近的三数之和
题目:
描述
给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。
只需要返回三元组之和,无需返回三元组本身
样例
样例 1:
输入:
numbers = [2,7,11,15]
target = 3
输出:
20
解释:
2+7+11=20
样例 2:
输入:
numbers = [-1,2,1,-4]
target = 1
输出:
2
public class Solution {
/**
* @param numbers: Give an array numbers of n integer
* @param target: An integer
* @return: return the sum of the three integers, the sum closest target.
*/
public int threeSumClosest(int[] nums, int target) {
// write your code here
Arrays.sort(nums);
int ans = 0, min = Integer.MAX_VALUE;
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
int l = 0, r = i - 1;
while(l < r) {
int sum = nums[l] + nums[r] + nums[i];
int diff = Math.abs(target - sum);
if(min > diff) {
min = diff;
ans = sum;
}
if(sum < target) {
l++;
while(l < r && nums[l] == nums[l - 1]) {
l++;
}
} else if(sum > target) {
r--;
while(l < r && nums[r] == nums[r + 1]) {
r--;
}
} else {
break ;
}
}
}
return ans;
}
}