16. 最接近的三数之和
难度中等838收藏分享切换为英文接收动态反馈
给定一个包括 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
int n = nums.size();sort(nums.begin(), nums.end());int mx = 1e7;auto upda = [&](int curr){if (abs(curr - target) < abs(mx - target))mx = curr;};for (int first = 0; first < n-1; ++first){if (first > 0 && nums[first] == nums[first - 1])continue;int second = first + 1, thr = n - 1;while (second < thr){int sum=nums[first] + nums[second] + nums[thr];if (sum == target)return target;upda(sum);if ((sum-target)<0){++second;}else{--thr;}if (second == thr)break;}}return mx;
