Table of Contents
Task
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
-10
4<= target <= 10
4
this problem was taken from Leetcode
Solution
Explanation:
- Sorting the array: This is necessary so that we can use the two-pointer technique effectively.
- Two pointers: For each element, we use two pointers to explore possible sums by adjusting their positions.
- Closest sum: We keep track of the closest sum throughout the iteration and update it whenever we find a sum closer to the target.
Check 3 Sum approach for more details.
function threeSumClosest(nums, target) { // Sort the array first nums.sort((a, b) => a - b); let closestSum = Infinity; // Iterate through the array for (let i = 0; i < nums.length - 2; i++) { let left = i + 1; let right = nums.length - 1; // Use two pointers to find the best sum while (left < right) { let currentSum = nums[i] + nums[left] + nums[right]; // Update the closest sum if needed if (Math.abs(currentSum - target) < Math.abs(closestSum - target)) { closestSum = currentSum; } // Move the pointers based on the current sum if (currentSum < target) { left++; } else if (currentSum > target) { right--; } else { // If the exact sum is found, return immediately return currentSum; } } } return closestSum; }