难度:中等
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
题目解析:
基于上一题的双指针法+排序,新申请两个变量,一个差值,另一个为三数之和,求差值最小的三数之和,像上一题一样分三种情况来考虑。
参考代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = 0;
if (nums.size() < 3)
return res;
int size = (int)nums.size();
int c_val = 20000;
//在使用双指针之前,首先进行快排(从小到大)
sort(nums.begin(), nums.end());
//固定前面一个值不变,后边使用双指针
for (int index = 0; index < size; ++index)
{
//初始化双指针
int left = index + 1;
int right = size - 1;
while (left < right)
{
//判断三种情况之一的相等情况
if ((nums[index] + nums[left] + nums[right]) == target)
{
return nums[index] + nums[left] + nums[right];
}//判断三种情况之一的三数之和大于0情况
else if ((nums[index] + nums[left] + nums[right]) > target)
{
//判断三数之和和target的差值
if (c_val > (nums[index] + nums[left] + nums[right] - target))
{
c_val = nums[index] + nums[left] + nums[right] - target;
res = nums[index] + nums[left] + nums[right];
}
--right;
}//判断三种情况之一的三数之和小于0情况
else if ((nums[index] + nums[left] + nums[right]) < target)
{
if (c_val > target - (nums[index] + nums[left] + nums[right]))
{
c_val = target - (nums[index] + nums[left] + nums[right]);
res = nums[index] + nums[left] + nums[right];
}
++left;
}
}
}
return res;
}
};
int main()
{
Solution solution;
vector<int> arr = { 0,2,1,-3 };
// vector<int> arr = {-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6};
vector<vector<int>> res;
cout << solution.threeSumClosest(arr,1) << endl;
system("pause");
return 0;
}