Sort first. For each element, use two pointers to find the pair giving sum closest to target.
function threeSumClosest(nums, target): sort(nums) closest = nums[0] + nums[1] + nums[2] for i in range(len(nums) - 2): left = i + 1 right = len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if abs(total - target) < abs(closest - target): closest = total if total == target: return total elif total < target: left += 1 else: right -= 1 return closest
time, space.