给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
排序+双指针
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = nums[0] + nums[1] + nums[2];
int first, second, third;
sort(nums.begin(), nums.end());
for (first = 0; first < nums.size() - 2; first ++) {
second = first + 1;
third = nums.size() - 1;
int temp = nums[first] + nums[second] + nums[third];
while (second < third) {
if (abs(temp - target) < abs(res - target))
res = temp;
if (temp == target)
return temp;
else if (temp < target)
second ++;
else
third --;
temp = nums[first] + nums[second] + nums[third];
}
}
return res;
}
};
这是一个关于算法的问题,要求在给定的整数数组中找到三个数,使它们的和与目标值最接近。解决方案是首先对数组进行排序,然后使用双指针法遍历数组,不断调整指针位置来找到最佳组合。该算法在力扣(LeetCode)上被称为'3Sum Closest'问题。

466

被折叠的 条评论
为什么被折叠?



