Find the triplet whose sum is closest to target (not necessarily equal). (LeetCode problem)
Brute force: every triplet, tracking the smallest absolute difference from target — O(n³).
Optimal — sort + two pointers, same shape as Three Sum: fix
one element, then move left/right based on whether the current sum is below or above target,
always tracking the closest sum seen. If an exact match is found, stop immediately — nothing can
be closer.
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int closestSum = Integer.MAX_VALUE / 2;
for (int i = 0; i < nums.length - 2; i++) { int left = i + 1; int 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 if (sum > target) { right--; } else { return sum; // exact match, can't get any closer } } }
return closestSum; }}Time: O(n²) (O(n log n) sort + O(n²) two-pointer scan). Space: O(1).