Let's solve this problem using a two-pointer approach after sorting the array. This is an extension of the 3Sum problem, but instead of finding an exact sum, we need to find the closest sum to the target.
Here's the solution in Python:
python
def threeSumClosest(nums, target):
nums.sort() # Sort the array first
n = len(nums)
closest_sum = float('inf') # Initialize closest sum to infinity
for i in range(n-2): # We need at least 3 numbers, so n-2
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
# If we found exact sum, return it
if current_sum == target:
return current_sum
# Update closest_sum if current_sum is closer to target
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
# If current sum is less than target, we need a larger sum
if current_sum < target:
left += 1
# If current sum is more than target, we need a smaller sum
else:
right -= 1
return closest_sum
# Test cases
print(threeSumClosest([-1,2,1,-4], 1)) # Output: 2
print(threeSumClosest([0,0,0], 1)) # Output: 0
Let's break down how this solution works:
First, we sort the array. This allows us to use the two-pointer technique efficiently.
We initialize closest_sum to infinity to ensure any sum we find will be closer than this initial value.
We iterate through the array with index i, and for each i:
We use two pointers: left (starting just after i) and right (starting at the end)
We calculate the current sum of the three numbers
For each sum we calculate:
If it equals the target, we return it immediately
If the absolute difference between current_sum and target is less than our previous closest sum's difference, we update closest_sum
If current_sum is less than target, we need a larger sum, so we increment left
If current_sum is more than target, we need a smaller sum, so we decrement right
Finally, we return the closest sum we found
Time Complexity: O(n²), where n is the length of the input array
Sorting takes O(n log n)
The two-pointer approach takes O(n²)
Overall complexity is dominated by O(n²)
Space Complexity: O(1) as we only use a constant amount of extra space (not counting the space needed for sorting, which depends on the sorting algorithm used)
The solution handles the given test cases correctly: