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).题意:给出一个数组及一个目标数,求数组中三个数加起来与目标数最接近的数
思路:与LeetCode 4Sum(backtrace+剪枝)有些相似
代码如下:
class Solution {
private int kSum(int[] nums, int start, int k,int cur_sum, int target)
{
int len = nums.length;
if (start >= len || 0 == k) return 0;
if (2 == k)
{
int end = len - 1;
int ans = Integer.MAX_VALUE;
while (start < end)
{
int sum = nums[start] + nums[end];
if (sum + cur_sum == target)
{
while (start < end && nums[start] == nums[start + 1]) start++;
start++;
while (start < end && nums[end] == nums[end - 1]) --end;
--end;
ans = target;
return ans;
}
else if (sum + cur_sum < target)
{
while (start < end && nums[start] == nums[start + 1]) start++;
start++;
if (Integer.MAX_VALUE == ans)
{
ans = cur_sum + sum;
}
else if (Math.abs(cur_sum + sum - target) < Math.abs(ans - target))
{
ans = cur_sum + sum;
}
}
else
{
while (start < end && nums[end] == nums[end - 1]) end--;
end--;
if (Integer.MAX_VALUE == ans)
{
ans = cur_sum + sum;
}
else if (Math.abs(cur_sum + sum - target) < Math.abs(ans - target))
{
ans = cur_sum + sum;
}
}
}
return ans;
}
int ans = Integer.MAX_VALUE;
for (int i = start; i <= (len - k); i++)
{
if (i > start && nums[i] == nums[i - 1]) continue;
int tmp = kSum(nums, i + 1, k - 1, cur_sum + nums[i], target);
if (Integer.MAX_VALUE == ans)
{
ans = tmp;
}
else if (Math.abs(tmp - target) < Math.abs(ans - target))
{
ans = tmp;
}
}
return ans;
}
public int threeSumClosest(int[] nums, int target)
{
Arrays.sort(nums);
int ans = kSum(nums, 0, 3, 0, target);
return ans;
}
}