思路: two pointer。其实这题就是第15题的变形(three sum)。具体来说就是先fix第一个数字(遍历),然后这时不是要找剩下的两个数字吗,这两个数字就用two pointer的方法来找。唯一的区别就是,这题可能会找不到三个数加起来等于target的,所以我们需要追踪三个数之合与target的差,存储最小的差。其他的实现和15题一模一样。话不多说,直接上代码:
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = 0;
int distance = Math.abs(nums[0] + nums[1] + nums[2] - target);
for(int i = 0; i < nums.length - 2; i++){
int left = i + 1, right = nums.length - 1, remain = target - nums[i];
while(left < right){
if(Math.abs(remain - nums[left] - nums[right]) <= distance){
distance = Math.abs(remain - nums[left] - nums[right]);
res = nums[i] + nums[left] + nums[right];
}
if(nums[left] + nums[right] == remain){
return nums[i] + nums[left] + nums[right];
}else if(nums[left] + nums[right] > remain){
right--;
}else{
left++;
}
}
}
return res;
}
}
总结:
- 求int绝对值: Math.abs(int n);