|
| 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> such that the sum is closest to <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> </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> </p> |
| 14 | +<p><strong>Constraints:</strong></p> |
| 15 | + |
| 16 | +<ul> |
| 17 | + <li><code>3 <= nums.length <= 10^3</code></li> |
| 18 | + <li><code>-10^3 <= nums[i] <= 10^3</code></li> |
| 19 | + <li><code>-10^4 <= target <= 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 | +``` |
0 commit comments