Given an integer array nums
of length n
and an integer target
, find three integers in nums
such that the sum is closest to target
.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
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).
Constraints:
3 <= nums.length <= 500
-1000 <= nums[i] <= 1000
-104 <= target <= 104
This problem asks us to find three numbers in a given array whose sum is closest to a target value. The most efficient approach involves sorting the array and then using a two-pointer technique.
Algorithm:
Sort the array: Sorting allows us to efficiently find combinations that are close to the target using two pointers. We sort the input nums
array in ascending order.
Iterate and use Two Pointers: We iterate through the sorted array using a single loop. For each element nums[i]
, we use two pointers, j
and k
, to explore the remaining elements:
j
starts at i + 1
(the element immediately after nums[i]
).k
starts at n - 1
(the last element of the array).Calculate the sum: In each iteration of the inner loop (controlled by j
and k
), we calculate the current sum: currentSum = nums[i] + nums[j] + nums[k]
.
Update the closest sum: We compare the absolute difference between currentSum
and the target
with the current minimum difference. If the new difference is smaller, we update closestSum
(which initially holds a very large value) and minDiff
.
Adjust pointers: Based on the relationship between currentSum
and target
:
currentSum
is less than target
, we increment j
to consider a larger number.currentSum
is greater than target
, we decrement k
to consider a smaller number.currentSum
equals target
, we've found the exact match, and we return target
.Return the closest sum: After iterating through all possible combinations, we return closestSum
, which holds the sum of the three numbers closest to the target
.
Time and Space Complexity:
Code Examples (with detailed comments):
The code examples provided in the original response cover multiple languages (Python, Java, C++, Go, TypeScript, JavaScript, C#, PHP). The structure is consistent across all languages. Here's a commented Python example to illustrate the key parts:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
# Sort the input array
nums.sort()
n = len(nums)
# Initialize closest sum and minimum difference (a large value initially)
closestSum = float('inf')
minDiff = float('inf')
for i in range(n - 2): # Iterate until the third-to-last element
j = i + 1
k = n - 1
while j < k: # Two-pointer approach
currentSum = nums[i] + nums[j] + nums[k]
diff = abs(currentSum - target)
# Update if a closer sum is found
if diff < minDiff:
minDiff = diff
closestSum = currentSum
# Adjust pointers based on the current sum
if currentSum < target:
j += 1
elif currentSum > target:
k -= 1
else: # Exact match found
return target
return closestSum # Return the closest sum found
The other language examples follow the same logic, adapting the syntax and libraries as needed. The core algorithm remains consistent to achieve an efficient O(n^2) time complexity solution.