Programming with Passion Algorithms, Mobile Development, Robotics

## Sunday, July 9, 2017

### 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:

    For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 

### 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.

Time complexity: $O(n^2)$
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; i0 && 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) target) r--; else return v; } } return res; }