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).
给定一个含n个整数的数组nums和一个整数target,从nums中找出三个整数,使它们的和最接近target,并返回这三个整数的和。可假定给定的nums和target只有一个解满足要求。
分析:
此题与3Sum类似,在此基础上稍作修改即可,将for中的while,改为三个数与target的差值的比较,越小越符合要求,找出差值最小的即可。注意因为排序了,当遍历到第i个元素时,若nums[i]*3>target,可提前结束遍历,因为i后面的任意三个元素的和只会更大。最终代码如下:
int threeSumClosest(vector<int>& nums, int target) {
int rst = INT_MAX;
int cnt = nums.size();
if (cnt <= 3)
{
rst = 0;
for (auto num : nums)
rst += num;
return rst;
}
sort(nums.begin(), nums.end());
int tmp = 0, left = 0, right = 0;
for (int i = 0; i < cnt - 2; i++)
{
if (nums[i] * 3 > target)
{
tmp = nums[i] + nums[i + 1] + nums[i + 2];
if (tmp < rst)
rst = tmp;
return rst;
}
left = i + 1;
right = cnt - 1;
while (left < right)
{
tmp = nums[i] + nums[left] + nums[right];
if (tmp == target)
return target;
if (abs(tmp-target) < abs(rst-target))
rst = tmp;
if (tmp < target)
left++;
else
right--;
}
}
return rst;
}
浙公网安备 33010602011771号