3Sum Closest

Given an integer array and a target, find the sum of three integers closest to the target. Sorting reduces the search to a fixed element plus a two-pointer sweep for the remaining two values.

Input Format

nums = array of integers, target = target sum

Output Format

closest three-number sum

Constraints

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

Examples

Example 1:

Input:

nums = [-1,2,1,-4]
target = 1

Output:

2

Explanation:

The sum 2 is the closest to target 1.

Example 2:

Input:

nums = [0,0,0]
target = 1

Output:

0

Explanation:

Only sum possible is 0.

Loading...
3Sum Closest - Sorting Based Array Problems