# 最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

 

示例:

输入:nums = [-1,2,1,-4], target = 1
输出:
2
解释:
与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

 

提示:

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

 

示例:

输入:nums = [-1,2,1,-4], target = 1
输出:
2
解释:
与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int arr[] = {-1, 2, 1, -4}; int target = 1; int length1 = sizeof(arr) / sizeof(arr[0]); vector nums(arr, arr + length1); int res; res = sol.threeSumClosest(nums, target); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: int threeSumClosest(vector &nums, int target) { if (nums.size() < 3) ; runtime_error("No Solution"); sort(nums.begin(), nums.end()); int res = nums[0] + nums[1] + nums[2]; int dValue = abs(target - res); int l, r, sum; for (int i = 0; i < nums.size() - 2; ++i) { l = i + 1; r = nums.size() - 1; if (3 * nums[i] > target) break; while (l < r) { sum = nums[i] + nums[l] + nums[r]; if (sum < target) --l; else if (sum > target) ++r; else return target; if (abs(target - sum) < dValue) { res = sum; dValue = abs(target - sum); } } } return res; } }; ``` ## 选项 ### A ```cpp class Solution { public: int threeSumClosest(vector &nums, int target) { int l = nums.size(); int best = nums[0] + nums[1] + nums[2]; for (int i = 0; i < l - 2; i++) { for (int j = i + 1; j < l - 1; j++) { for (int k = j + 1; k < l; k++) { int t = nums[i] + nums[j] + nums[k]; if (abs(t - target) < abs(best - target)) { best = t; } } } } return best; } }; ``` ### B ```cpp class Solution { public: int threeSumClosest(vector &nums, int target) { sort(nums.begin(), nums.end()); if (nums.size() < 3) return {}; int closest = target + 10000000; for (int i = 0; i < nums.size() - 2; i++) { int fix = nums[i]; if (fix > target && abs(fix + nums[i + 1] + nums[i + 2] - target) > abs(closest - target)) break; for (int j = i + 1; j < nums.size() - 1; j++) { for (int k = j + 1; k < nums.size(); k++) { int temp = abs(target - fix - nums[j] - nums[k]); if (temp < abs(closest - target)) closest = fix + nums[j] + nums[k]; } } } return closest; } }; ``` ### C ```cpp class Solution { public: int threeSumClosest(vector &nums, int target) { int len = nums.size(); int min = target + 1000000; sort(nums.begin(), nums.end()); for (int i = 0; i < len; i++) { int fir = nums[i]; int r = len - 1; int l = i + 1; if (i > 0 && fir == nums[i - 1]) continue; if (l >= r) break; while (l < r) { if (nums[l] + nums[r] + fir == target) return target; if (nums[l] + nums[r] < target - fir) { int temp = target - fir - nums[r] - nums[l]; if (temp < abs(min - target)) min = nums[l] + nums[r] + fir; l++; } else if (nums[l] + nums[r] > target - fir) { int temp = nums[l] + nums[r] + fir - target; if (temp < abs(min - target)) min = nums[l] + nums[r] + fir; r--; } } } return min; } }; ```