### Problem

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

#### Example:

```
```

### Solution

This problem is identical to 3Sum. The difference being, instead of returning all sums, we return the (first) closest sum to the target. This simplification results in maintaining a solution with minimum distance to the target, `mind`

in the code below, instead of checking for equivalence with the target and storing in a list.

Space complexity: $O(1)$

Runtime: 18 ms (96.18%)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public int threeSumClosest(int[] nums, int target) { if (nums==null || nums.length < 3) return 0; Arrays.sort(nums); // System.out.println(Arrays.toString(nums)); int l, r, v, len=nums.length, res=0, mind=Integer.MAX_VALUE; for (int i=0; i<len-1; i++) { if (i>0 && nums[i-1]==nums[i]) continue; l = i+1; r = len-1; while (l < r) { v = nums[i]+nums[l]+nums[r]; if (Math.abs(v-target)<mind) { mind = Math.abs(v-target); res = v; } if (v < target) l++; else if (v > target) r--; else return v; } } return res; } |