Leetcode 16、最接近的三数之和

排序+指针
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
int res = 10000000;
for(int i = 0; i < len; i++) {
if(i != 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1, k = len - 1;
while(j < k) {
// 如果当前三数之和等于target,直接返回target
int curr = nums[i] + nums[j] + nums[k];
if(curr == target) return target;
// 如果当前curr和target的差值小于res和target的差值,更新res。
if(Math.abs(curr - target) < Math.abs(res - target)) {
res = curr;
}
/**
如果当前curr的值小于target,因为nums数组已经被排序,所以
j向右移动到一个新的值的位置
curr大于target的值,则左移k
**/
if(curr < target) {
int j0 = j + 1;
while(j0 < k && nums[j0] == nums[j]) {
j0++;
}
j = j0;
}else{
int k0 = k - 1;
while(k0 > j && nums[k0] == nums[k]) {
k0--;
}
k = k0;
}
}
}
return res;
}
}
4634

被折叠的 条评论
为什么被折叠?



