16. 最接近的三数之和
题目链接
与上一题一样的方法
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
int ans = nums[0] + nums[1] + nums[2];
for(int i = 0; i < n-2; i++){
if(i > 0 && nums[i] == nums[i-1]) continue;
int k = n-1;
for(int j = i+1; j < n-1; j++){
int sum = nums[i] + nums[j];
if(j > i+1 && nums[j] == nums[j-1]) continue;
while(k > j && nums[k] + sum > target){
if(Math.abs(nums[k] + sum - target) < Math.abs(ans - target)){
ans = nums[k] + sum;
}
k--;
}
if(k == j) break;
if(Math.abs(nums[k] + sum - target) < Math.abs(ans - target)){
ans = nums[k] + sum;
}
}
}
return ans;
}
}
- 在移动k的时候顺便判断一下有没有更接近target
- 移动完先更新ans,再继续
两个指针一起动的简单写法
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
int ans = nums[0] + nums[1] + nums[2];
for(int i = 0; i < n-2; i++){
if(i > 0 && nums[i] == nums[i-1]) continue;
int j = i + 1, k = n-1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum == target)
return target;
if(Math.abs(sum - target) < Math.abs(ans - target))
ans = sum;
if(sum < target){
j++;
while(j < k && nums[j] == nums[j-1])
j++;
}
else {
k--;
while(k > j && nums[k] == nums[k+1])
k--;
}
}
}
return ans;
}
}
- 既然每动一下都要判断,那就没有必要先for循环j再while循环k了
- 直接一个while循环,大了就k--,小了就j++,相等直接return