代码
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[] numbers, int target) {
// write your code here
if(numbers==null||numbers.length<=0){
return 0;
}
Arrays.sort(numbers);
int ans = Integer.MAX_VALUE;
for(int i=0; i<numbers.length; i++){
for(int j=i+1, k=numbers.length-1; j<k;){
int sum = numbers[i]+numbers[j]+numbers[k];
// update the closest answer
ans = (Math.abs(target-sum)<Math.abs(target-ans) ? sum:ans);
if (sum > target) --k;
else if (sum < target) ++j;
else return sum; // sum equal to target
}
}
return ans;
}
}