Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1.
The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
The same problem, not on a difficult question, Bishi can
Java implementations:
static public int threesumclosest (int[] nums, int target) {int result = Nums[0] + nums[1] + nums[2]; Arrays.sort (Nums); for (int i = 0; i < nums.length-2; i++) {Int J = i + 1, k = Nums.length-1;while (J < k) {if (M Ath.abs (Nums[i] + nums[j] + nums[k]-target) < Math.Abs (result-target)) result = Nums[i] + nums[j] + nums[k];if (nums [i] + nums[j] + Nums[k] < target) J++;else if (Nums[i] + nums[j] + nums[k] > target) k--;elsereturn target;//without while loop can also pass the test, but the time will be slightly longer while (I < k && Nums[i] = = nums[i + 1]) i++; }}return result;}
Java for Leetcode 016 3Sum Closest