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).
Translation: Given an array of nums integers, and a goal and target, find the array of three numbers and closest to target, return this and you can
Idea: Similar to threesum, just do not mark the position of these three numbers, just return three numbers and the minimum value difference from target.
When summing, use the twosum procedure, at which target = Target-num[i], and then return the minimum value of 2 numbers and the difference from the new target.
Note: Be sure to use absolute values when representing the minimum difference. That is Math.Abs ().
Code:
public static int threesumclosest (int[] nums, int target) { if (nums = = NULL | | Nums.length < 3) return Integer. Min_value; Arrays.sort (nums); int min = nums[0] + nums[1] + nums[2]-target;//minimum spacing for (int i = 0; i < nums.length-2;i++)//Guaranteed nums.length-1 and Nums.length-2 { int close= twosum (nums,i+1,target-nums[i]);//calculation of the remaining 2 nearest value if (math.abs (min) > Math.Abs (Close)) min = close; } return target+min; } public static int twosum (int []num,int start, int target) {int min = Num[start] + num[start+1]-target;//find minimum spacing int l = Star T;int r = Num.length-1;while (L < R) {if (num[l]+num[r]==target)//If returns return 0;int close = Num[l] + num[r]-target;if (Ma Th.abs (Close) <math.abs (min)) min = close;if (Num[l]+num[r] > target) {r--;} else l++;} return min;}
Recent Review network security, plus 51 holiday, brush the problem a few days, sin sin!
But after some days there are also UML exams. Be sure to insist!!!
Leetcode 3Sum Closest Find the three numbers closest to the specified target and