Skip to content

Latest commit

 

History

History
55 lines (45 loc) · 1.8 KB

README.md

File metadata and controls

55 lines (45 loc) · 1.8 KB

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;
    }
};