【双指针】LeetCode 16. 最接近的三数之和
题目链接
思路
借鉴 【双指针】LeetCode 15. 三数之和 的思路,只不过把0换成 target
代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = 0x3f3f3f3f;
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i - 1] == nums[i]){
continue;
}
int j = i + 1;
int k = nums.length - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(distance(result, target) > distance(sum, target)){
result = sum;
}
if(sum > target){
k--;
}else{
j++;
}
}
}
return result;
}
private int distance(int sum, int target){
return Math.abs(target - sum);
}
}