16. 3Sum Closest
Explanation:
To solve this problem, we can follow these steps:
- Sort the input array
nums
. - Initialize a variable
closestSum
to store the closest sum found so far. - Iterate over the array
nums
up to the third last element. - Inside the loop, use two pointers
left
andright
to find the other two numbers for the current number. - Calculate the current sum of the three numbers and update
closestSum
if the current sum is closer to the target. - Update the pointers based on whether the current sum is less than or greater than the target.
- Continue iterating until all possible combinations are checked.
Time complexity: O(n^2) where n is the length of the input array nums
.
Space complexity: O(1)
import java.util.Arrays;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closestSum = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (Math.abs(sum - target) < Math.abs(closestSum - target)) {
closestSum = sum;
}
if (sum < target) {
left++;
} else {
right--;
}
}
}
return closestSum;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.