#16

3Sum Closest

specialist · 895 · lc medium +31 · verified · 48.1% accepted · 11,571 likes · top 34%

play →

Description

From integer array nums of length n, select three elements at distinct positions whose sum is nearest to target and return that sum. Exactly one closest sum is guaranteed.

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).

Example 2:

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

Code

1
2
3