Three Sum Closest
Problem statement
Given an integer array nums and an integer target, choose three distinct indices and return the sum of their values that is closest to target.
If two obtainable sums are equally close, return the smaller sum.
Function
threeSumClosest(nums: int[], target: int) → intExamples
Example 1
nums = [-1,2,1,-4]target = 1return = 2The closest sum is -1 + 2 + 1 = 2.
Example 2
nums = [0,0,0]target = 1return = 0The only possible sum is 0.
Example 3
nums = [-2,0,2,4]target = 1return = 0Sums 0 and 2 are both one away, so the smaller sum 0 is returned.
Constraints
3 <= nums.length <= 1000.-10^4 <= nums[i], target <= 10^4.- The answer fits in a signed 32-bit integer.