Topic
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).
Resolution
and 3Sum problem-solving report is very similar, and the difference is not to ask for three number and is not 0, but to see whether the difference between three number and target is the smallest, just record the current optimal solution and constantly update its value can be.
"Java Code" O (n^2)
public class Solution {public int threesumclosest (int[] num, int target) {if (num = = NULL | | Num.length < 3 ) return 0; Arrays.sort (num); int ret = 0; int closestdist = Integer.max_value; int len = num.length; for (int i = 0; i < len-2; i++) {if (i > 0 && num[i] = = Num[i-1]) continue; int L = i+1, r = len-1; while (L < r) {int sum = Num[i] + num[l] + num[r]; if (sum < target) {if (Target-sum < closestdist) {closestdist = target- Sum ret = sum; } l++; } else if (Sum > Target) {if (Sum-target < closestdist) {closestdist = s Um-target; ret = sum; } r--; } else {//when sum = = TargeT, return sum. return sum; }}} return ret; }}
Error prone is to set the RET initial value to Integer.max_value, and then calculate closestdist = Math.Abs (Ret-target), which will cause overflow!!
"Leetcode" 3Sum Closest Problem Solving report (Java)