Skip to content

Commit c0ebaa9

Browse files
committed
16
1 parent dc29d15 commit c0ebaa9

File tree

2 files changed

+55
-22
lines changed

2 files changed

+55
-22
lines changed

leetcode/16. 3Sum Closest/README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# [16. 3Sum Closest (Medium)](https://leetcode.com/problems/3sum-closest/submissions/)
2+
3+
<p>Given an array <code>nums</code> of <em>n</em> integers and an integer <code>target</code>, find three integers in <code>nums</code>&nbsp;such that the sum is closest to&nbsp;<code>target</code>. Return the sum of the three integers. You may assume that each input would have exactly one solution.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong>Example 1:</strong></p>
7+
8+
<pre><strong>Input:</strong> nums = [-1,2,1,-4], target = 1
9+
<strong>Output:</strong> 2
10+
<strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
11+
</pre>
12+
13+
<p>&nbsp;</p>
14+
<p><strong>Constraints:</strong></p>
15+
16+
<ul>
17+
<li><code>3 &lt;= nums.length &lt;= 10^3</code></li>
18+
<li><code>-10^3&nbsp;&lt;= nums[i]&nbsp;&lt;= 10^3</code></li>
19+
<li><code>-10^4&nbsp;&lt;= target&nbsp;&lt;= 10^4</code></li>
20+
</ul>
21+
22+
23+
**Related Topics**:
24+
[Array](https://leetcode.com/tag/array/), [Two Pointers](https://leetcode.com/tag/two-pointers/)
25+
26+
**Similar Questions**:
27+
* [3Sum (Medium)](https://leetcode.com/problems/3sum/)
28+
* [3Sum Smaller (Medium)](https://leetcode.com/problems/3sum-smaller/)
29+
30+
## Solution 1.
31+
32+
```cpp
33+
// OJ: https://leetcode.com/problems/3sum-closest/
34+
// Author: github.com/lzl124631x
35+
// Time: O(N^2)
36+
// Space: O(1)
37+
class Solution {
38+
public:
39+
int threeSumClosest(vector<int>& A, int target) {
40+
sort(begin(A), end(A));
41+
int diff = INT_MAX;
42+
for (int i = 0, N = A.size(); i < N; ++i) {
43+
int L = i + 1, R = N - 1;
44+
while (L < R) {
45+
int sum = A[L] + A[R] + A[i];
46+
if (sum == target) return target;
47+
if (abs(target - sum) < abs(diff)) diff = target - sum;
48+
if (sum > target) --R;
49+
else ++L;
50+
}
51+
}
52+
return target - diff;
53+
}
54+
};
55+
```

leetcode/16. 3Sum Closest/s1.cpp

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)