LeetCode刷题笔记之16.最接近的三数之和
题目
解题方法:排序 + 双指针
将数组排序,枚举a,从a的右边第一位起,借助双指针一个从左一个从右枚举b和c;
a是固定的,b+c>target则c左移;
a是固定的,b+c<target则b右移;
如果这次a+b+c-target小于上次的值。更新这个值。
最后将这个值返回。
代码
package com.leecode;
import java.util.Arrays;
public class Solution16 {
public int threeSumClosest(int[] nums, int target) {
//排序
Arrays.sort(nums);
//设置最接近的值。
int best = 10000000;
int n = nums.length;
//枚举a
for (int i = 0; i < n; i++) {
//优化,枚举a的时候避免重复
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
//使用双指针枚举b,c;
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
//如果相等直接返回
if (sum == target) {
return sum;
}
//根据绝对值的差值跟新best
if (Math.abs(sum - target) < Math.abs(best - target)) {
best = sum;
}
// 如果和大于 target,左移 c 对应的指针
if (sum > target) {
int k0 = k - 1;
//移动到下一个不相等的元素
while (j < k0 && nums[k0] == nums[k]) {
k0--;
}
k = k0;
} else {
//如果小于target,右移b对应的指针
int j0 = j + 1;
//移动到下一个不相等的元素
while (j0 < k && nums[j0] == nums[j]) {
j0++;
}
j = j0;
}
}
}
return best;
}
}
欢迎各位讨论指正!