16. 3Sum Closest

https://leetcode.com/problems/3sum-closest/

Problem

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

Solution

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int min_diff = INT_MAX;
        for (int i = 0; i < nums.size(); ++i) {
            int begin = i + 1, end = nums.size() - 1;
            while (begin < end) {
                const int threesum = nums[i] + nums[begin] + nums[end];
                const int diff = threesum - target;
                if (abs(min_diff) > abs(diff)) min_diff = diff;
                
                if (diff == 0) return target;
                else if (diff > 0) --end;
                else ++begin;
            }
        }
        return target + min_diff;
    }
};
  • #twopointer

  • #important

Last updated

Was this helpful?