Skip to content

Latest commit

 

History

History
 
 

16. 3Sum Closest

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 

Constraints:

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

Related Topics:
Array, Two Pointers

Similar Questions:

Solution 1. Two pointers

// OJ: https://leetcode.com/problems/3sum-closest/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
    int threeSumClosest(vector<int>& A, int target) {
        sort(begin(A), end(A));
        int diff = INT_MAX;
        for (int i = 0, N = A.size(); i < N; ++i) {
            int L = i + 1, R = N - 1;
            while (L < R) {
                int sum = A[L] + A[R] + A[i];
                if (sum == target) return target;
                if (abs(target - sum) < abs(diff)) diff = target - sum;
                if (sum > target) --R;
                else ++L;
            }
        }
        return target - diff;
    }
};