最接近的三数之和

给定一个包括 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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) {
return 0;
}
sort(nums.begin(), nums.end());
int close = nums[0] + nums[nums.size() - 2] + nums[nums.size() - 1];
for (int i = 0; i < nums.size() - 2; ++i) {
for (int start = i + 1, end = nums.size() - 1; start < end; ) {
int sum = nums[i] + nums[start] + nums[end];
if (abs(sum - target) < abs(close - target)) {
close = sum;
}
if (sum < target) {
start++;
} else if (sum > target) {
end--;
} else {
return target;
}
}
}
return close;
}
};

int main() {
vector<int> input = {-1,2,1,-4};
std::cout << Solution().threeSumClosest(input, 1) << std::endl; // 2
input = {1,1,1,0};
std::cout << Solution().threeSumClosest(input, -100) << std::endl; // 2
input = {1,2,4,8,16,32,64,128};
std::cout << Solution().threeSumClosest(input, 82) << std::endl; // 82
input = {1,2,5,10,11};
std::cout << Solution().threeSumClosest(input, 12) << std::endl; // 13
}