3Sum Closest
medium
arrays
two-pointers
sorting
Given an integer array nums of length at least 3 and an integer target, choose three distinct indices i, j, and k and return the sum nums[i] + nums[j] + nums[k] whose value is closest to target.
You only need to return the closest sum, not the actual triplet.
Input / output
- Input:
nums: int[],target: int - Output:
int
Examples
nums = [-1, 2, 1, -4],target = 1returns2because(-1 + 2 + 1) = 2, which is closest to1.nums = [0, 0, 0],target = 1returns0.nums = [1, 2, 4],target = 8returns7because that is the only possible triplet sum.
Constraints
3 <= nums.length <= 500-1000 <= nums[i] <= 1000-10^4 <= target <= 10^4- Exactly one sum is closest to
targetin the test data, so no tie-breaking rule is needed between two different sums.
Follow-up
Can you improve the brute-force O(n^3) search by sorting the array first and then using a two-pointer scan for each fixed first value?
Examples
Example 1
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Example 2 (all zeros)
Input: nums = [0,0,0], target = 1
Output: 0