Skip to content

Commit 1e2ed97

Browse files
committed
add leetcode c++11 solution: 016._3Sum_Closest.md
1 parent 4afc3b5 commit 1e2ed97

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## 16. 3Sum Closest
2+
3+
难度:Medium
4+
5+
## 内容
6+
7+
> 原题链接:https://leetcode.com/problems/3sum-closest/description/
8+
9+
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.
10+
11+
Example:
12+
13+
```
14+
Given array nums = [-1, 2, 1, -4], and target = 1.
15+
16+
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
17+
```
18+
19+
## 思路
20+
21+
先排序,遍历第一个数,第二和第三个数通过双指针查找,转化为2sum closest的问题。如果遇到和等于target的三个数,直接返回target。
22+
23+
## 代码
24+
25+
```
26+
class Solution {
27+
public:
28+
int threeSumClosest(vector<int>& nums, int target) {
29+
std::sort(nums.begin(), nums.end());
30+
int min_distance{INT_MAX}, sum{0}, cur_sum{0};
31+
for (auto it = nums.cbegin(); it != nums.cend(); ++it)
32+
for (auto left_idx = std::next(it), right_idx = std::prev(nums.cend()); left_idx < right_idx; cur_sum > target ? --right_idx : ++left_idx) {
33+
cur_sum = *it + *left_idx + *right_idx;
34+
auto cur_distance = std::abs(cur_sum - target);
35+
if (cur_sum == target)
36+
return target;
37+
else if (cur_distance < min_distance) {
38+
min_distance = cur_distance;
39+
sum = cur_sum;
40+
}
41+
}
42+
return sum;
43+
}
44+
};
45+
```

0 commit comments

Comments
 (0)