16. 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题意,选择任意三个数字,相加合之后,再和我们已知的target做比较,选出最为接近的一个合的值。
java:
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest = target - nums[0] - nums[1] - nums[2];
for (int i = 0; i < nums.length; i++) {
int l = i + 1;
int r = nums.length - 1;
int newTarget = target - nums[i];
while (l < r) {
if (nums[l] + nums[r] == newTarget) {
return target;
}
int diff = newTarget - nums[l] - nums[r];
if (Math.abs(diff) < Math.abs(closest)) {
closest = diff;
}
if (nums[l] + nums[r] < newTarget) {
l++;
} else {
r--;
}
}
}
return target - closest;
}
}
网友评论