Title: Given An array S of n integers, find three integers in S such so the sum is closest to a G Iven 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).
Analysis: This topic gives us a nums array and a target, which allows us to find a set of three numbers and is closest to target. Since we have done the sum of three numbers, so it is almost the same way to do this problem (here is fully explained, to honestly follow the question number, the first topic can be used to assist after the problem). The method is to sort the array first, why to sort it, because to use the second pointers to traverse to find the sum of two, only after the small to large order of results, can be moved according to the situation left and right. When the first number is determined, the sum of two numbers is found in the remaining array, plus the first number, the temp_sum minus the target to get Temp_diff, if the Temp_diff is smaller than the previous one, then update diff and Closestsum. Using the Pointers feature, if the temp_sum is smaller than target, it means that we need a larger sum, so let left++ get a larger sum. If Temp_sum is larger than target, we need a smaller sum. If they are equal, return directly. Because all are equal, then the difference is equal to 0, there will be no difference between the smaller.
classSolution { Public intThreesumclosest (int[] Nums,inttarget) { intCloseTarget = Nums[0] + nums[1] + nums[2]; Arrays.sort (Nums); intMinreduce = Math.Abs (CloseTarget-target); for(inti=0;i<nums.length-2;i++){ intleft = I+1,right = Nums.length-1; while(Left <Right ) { intTotal = nums[left]+nums[right]+Nums[i]; if(total==target)returnTarget; Else if(total<target) { Left++; }Else Right--; if(Minreduce > Math.Abs (total-target)) {Minreduce= Math.Abs (Total-target); CloseTarget=Total ; } } } returnCloseTarget; }}
[Leetcode] 16. 3Sum Closest Java