3Sum Closest (M)
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题意
求一三元对,使其和最接近给定的值。
思路
与 15. 3Sum 类似,只是修改了判定的标准。先排序,后利用two pointers并去除重复值即可。
代码实现
class Solution {
public int threeSumClosest(int[] nums, int target) {
int min = Integer.MAX_VALUE;
int ans = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// 去除重复的i
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1, k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
int diff = Math.abs(sum - target);
if (diff < min) {
min = diff;
ans = sum;
}
// 移动j、k的标准是使sum更加接近target
if (sum < target) {
j++;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
} else if (sum > target) {
k--;
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
} else {
return sum; // 特殊情况,sum正好为target
}
}
}
return ans;
}
}