16 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

1
2
3
Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

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

1
2
3
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

想法

实际上和15. 3 Sum比较相似,只不过在原先是判断和是否等于0,这个需要记录三个数和目标值的差值的最小值最后返回即可。注意比较差值时需要比较绝对值。

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
43
44
45
46
47
48
49
50
51
52
53

#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

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

int main(void)
{
Solution s;
vector<int> nums = {1, 1, 1};
int target = 1;
cout << s.threeSumClosest(nums, target) << endl;
return 0;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×